def test_deploy_networkipv6_configuration_with_inactive_vlan(self):
        self.networkv6.vlan.ativada = False

        self.mock_ip_get_by_blocks_and_net(
            Ipv6(block1='fff',
                 block2='fff',
                 block3='fff',
                 block4='fff',
                 block5='fff',
                 block6='fff',
                 block7='fff',
                 block8='fff'))
        self.mock_find_equipamento_ipv6([Ipv6Equipament()])
        self.mock_find_roteiro(
            EquipamentoRoteiro(roteiro=Roteiro(roteiro='roteiro')))
        self.mock_template_file_read('script content')
        deploy_config_mock = self.mock_deploy_config('config_deployed')
        network_activation_mock = self.mock_networkv6_activation()
        vlan_activation_mock = self.mock_vlan_activation()

        response = deploy_networkIPv6_configuration(self.user, self.networkv6,
                                                    self.equipment_list)

        self.assertTrue(deploy_config_mock.called)
        network_activation_mock.assert_called_with(self.user)
        vlan_activation_mock.assert_called_with(self.user)
        self.assertEquals({1: 'config_deployed'}, response)
Пример #2
0
def _update_pool_member(members):
    """Updates pool members"""
    for member in members:
        ip = Ip.get_by_pk(member['ip']['id']) if member['ip'] else None
        ipv6 = Ipv6.get_by_pk(member['ipv6']['id']) if member['ipv6'] else None

        pool_member = ServerPoolMember.objects.get(id=member['id'])
        pool_member.ip = ip
        pool_member.ipv6 = ipv6
        pool_member.weight = member['weight']
        pool_member.priority = member['priority']
        pool_member.port_real = member['port_real']
        pool_member.member_status = member['member_status']
        pool_member.limit = member['limit']
        pool_member.save()

        if pool_member.server_pool.dscp:
            if pool_member.port_real != pool_member.server_pool.default_port:

                mb_name = '{}:{}'.format(
                    (ip.ip_formated if ip else ipv6.ip_formated),
                    member['port_real'])

                raise ValidationAPIException(
                    'DRSL3 Restriction: Pool Member {} cannot have different '
                    'port of Pool {}'.format(
                        mb_name, pool_member.server_pool.identifier))
Пример #3
0
def get_ipv6_by_id(ip_id):
    """Get Ipv6."""

    try:
        network = Ipv6.get_by_pk(ip_id)
    except IpNotFoundError, e:
        raise ObjectDoesNotExistException(e.message)
Пример #4
0
    def test_update_pool_member(self):
        save_member_mock = patch(
            'networkapi.requisicaovips.models.ServerPoolMember.save').start()

        pool = ServerPool(id=1, default_limit=1)
        pool_member = ServerPoolMember()
        dict = {
            'nome_equips': 'equip_name',
            'weight': 1,
            'priority': 1,
            'port_real': 80
        }
        ip = Ip(id=1)
        ipv6 = Ipv6(id=1)
        update_pool_member(pool, pool_member, dict, ip, ipv6, self.user)

        self.assertEquals(pool, pool_member.server_pool)
        self.assertEquals(1, pool_member.limit)
        self.assertEquals(ip, pool_member.ip)
        self.assertEquals(ipv6, pool_member.ipv6)
        self.assertEquals('equip_name', pool_member.identifier)
        self.assertEquals(1, pool_member.weight)
        self.assertEquals(1, pool_member.priority)
        self.assertEquals(80, pool_member.port_real)
        self.assertTrue(save_member_mock.called)
Пример #5
0
def get_ip_objects(dic):
    ip_object = None
    ipv6_object = None
    if len(dic['ip']) <= 15:
        ip_object = Ip.get_by_pk(dic['id'])
    else:
        ipv6_object = Ipv6.get_by_pk(dic['id'])
    return ip_object, ipv6_object
Пример #6
0
def get_ip_objects(dic):
    ip_object = None
    ipv6_object = None
    if len(dic['ip']) <= 15:
        ip_object = Ip.get_by_pk(dic['id'])
    else:
        ipv6_object = Ipv6.get_by_pk(dic['id'])
    return ip_object, ipv6_object
Пример #7
0
def create_ipv6(ipv6, user):
    """Creates a Ipv6."""

    try:
        ipv6_obj = Ipv6()
        ipv6_obj.create_v4(ipv6)
    except ObjectDoesNotExistException, e:
        raise ObjectDoesNotExistException(e.detail)
Пример #8
0
	def create(self, ipv6_id, networkipv6_id):
		ipv6 = Ipv6.get_by_pk(ipv6_id)
		networkipv6 = NetworkIPv6.get_by_pk(networkipv6_id)

		if len(DHCPRelayIPv6.objects.filter(ipv6=ipv6, networkipv6=networkipv6)) > 0:
			raise exceptions.DHCPRelayAlreadyExistsError(ipv6_id, networkipv6_id)
		
		self.ipv6 = ipv6
		self.networkipv6 = networkipv6
Пример #9
0
    def test_get_ipv6(self):
        get_by_pk_mock = patch('networkapi.ip.models.Ipv6.get_by_pk').start()
        get_by_pk_mock.return_value = Ipv6()

        ip = get_ip_objects({
            'ip': '2001:0db8:85a3:08d3:1319:8a2e:0370:7344',
            'id': 1
        })

        self.assertTrue(isinstance(ip[1], Ipv6))
        self.assertIsNone(ip[0])
Пример #10
0
def update_vip_request(vip_request, user):
    """
    update Vip Request
    """

    vip = models.VipRequest.get_by_pk(vip_request['id'])

    vip.name = vip_request['name']
    vip.service = vip_request['service']
    vip.business = vip_request['business']
    vip.environmentvip_id = vip_request['environmentvip']
    vip.ipv4 = Ip.get_by_pk(
        vip_request['ipv4']) if vip_request['ipv4'] else None
    vip.ipv6 = Ipv6.get_by_pk(
        vip_request['ipv6']) if vip_request['ipv6'] else None

    option_ids = [
        int(option.optionvip.id)
        for option in vip.viprequestoptionvip_set.all()
    ]
    options = [
        int(vip_request['options'][key]) for key in vip_request['options']
    ]
    option_remove = list(set(option_ids) - set(options))
    option_create = list(set(options) - set(option_ids))

    vip.save()

    _update_port(vip_request['ports'], vip)

    _create_option(option_create, vip.id)
    _delete_option(option_remove, vip.id)

    dsrl3 = OptionVip.objects.filter(
        nome_opcao_txt='DSRL3', tipo_opcao='Retorno de trafego').values('id')
    if dsrl3:
        if dsrl3[0]['id'] in option_remove:
            models.VipRequestDSCP.objects.filter(vip_request=vip.id).delete()

    # perms
    groups_perm = vip_request.get('groups_permissions', [])
    groups_perm += facade_usr.get_groups(
        vip_request.get('users_permissions', []))
    groups = facade_usr.reduce_groups(groups_perm)

    perm = vip_request.get('permissions')
    perm_replace = perm.get('replace') if perm else False

    update_groups_permissions(groups, vip.id, user, perm_replace)

    # sync with old tables
    syncs.new_to_old(vip)
Пример #11
0
def _create_pool_member(members, pool):
    """Creates pool members"""
    for member in members:
        ip = Ip.get_by_pk(member['ip']['id']) if member['ip'] else None
        ipv6 = Ipv6.get_by_pk(member['ipv6']['id']) if member['ipv6'] else None
        identifier = ip.ip_formated if ip else ipv6.ip_formated

        pool_member = ServerPoolMember()
        pool_member.server_pool = pool
        pool_member.ip = ip
        pool_member.ipv6 = ipv6
        pool_member.identifier = identifier
        pool_member.weight = member['weight']
        pool_member.priority = member['priority']
        pool_member.port_real = member['port_real']
        pool_member.member_status = member['member_status']
        pool_member.limit = member['limit']
        pool_member.save()

        # vip with dsrl3 using pool
        if pool.dscp:

            mbs = pool_member.get_spm_by_eqpt_id(pool_member.equipment.id)

            # check all the pools related to this pool vip request to filter
            # dscp value
            related_viprequestports = pool.vips[0].viprequestport_set.all()
            vippools = [
                p.viprequestportpool_set.all()[0].server_pool_id
                for p in related_viprequestports
            ]

            sps = ServerPool.objects.filter(serverpoolmember__in=mbs).exclude(
                id__in=vippools)
            dscps = [sp.dscp for sp in sps]

            mb_name = '{}:{}'.format(
                (ip.ip_formated if ip else ipv6.ip_formated),
                member['port_real'])
            if pool.dscp in dscps:
                raise ValidationAPIException(
                    'DRSL3 Restriction: Pool Member {} cannot be insert'
                    ' in Pool {}, because already in other pool'.format(
                        mb_name, pool.identifier))

            if pool_member.port_real != pool.default_port:
                raise ValidationAPIException(
                    'DRSL3 Restriction: Pool Member {} cannot have different'
                    ' port of Pool {}'.format(mb_name, pool.identifier))
    def test_deploy_networkipv6_configuration_given_gateway_equipment_not_found(
            self):
        self.mock_ip_get_by_blocks_and_net(
            Ipv6(block1='fff',
                 block2='fff',
                 block3='fff',
                 block4='fff',
                 block5='fff',
                 block6='fff',
                 block7='fff',
                 block8='fff'))
        self.mock_find_equipamento_ipv6([])

        with self.assertRaises(IncorrectRedundantGatewayRegistryException):
            deploy_networkIPv6_configuration(self.user, self.networkv6,
                                             self.equipment_list)
Пример #13
0
def get_id_ip(real):
    """
        Get real id_ip by octs/block and equipment
    """
    equip = Equipamento().get_by_name(real['real_name'])

    # Check ip type
    if is_valid_ipv4(real['real_ip']) is True:
        oct = real['real_ip'].split('.')
        ip = Ip().get_by_octs_equipment(
            oct[0], oct[1], oct[2], oct[3], equip.id)
    else:
        block = real['real_ip'].split(':')
        ip = Ipv6().get_by_blocks_equipment(block[0], block[1], block[2], block[
            3], block[4], block[5], block[6], block[7], equip.id)

    return ip.id
Пример #14
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv6 by id.

        URLs: ip/get-ipv6/id_ip
        """

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_ip = kwargs.get('id_ip')

            if not is_valid_int_greater_zero_param(id_ip):
                raise InvalidValueError(None, 'id_ip', id_ip)

            # Business Rules

            ip = Ipv6()
            ip = ip.get_by_pk(id_ip)

            ip_map = dict()
            equip_list = []

            for ipequip in ip.ipv6equipament_set.all():
                equip_list.append(ipequip.equipamento.nome)

            # IP map
            ip_map = model_to_dict(ip)
            ip_map['equipamentos'] = equip_list if len(
                equip_list) > 0 else None

            # Return XML
            return self.response(dumps_networkapi({'ipv6': ip_map}))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
Пример #15
0
    def handle_get(self, request, user, *args, **kwargs):
        '''Handles GET requests get an IP6 available.

        URL: ip/availableip6/ip_rede
        '''

        self.log.info('Get an IP6 available')

        try:
            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_network6 = kwargs.get('id_rede')

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

            # Business Rules

            ip6 = Ipv6.get_available_ip6(id_network6)

            list_ip = []
            list_ip.append(ip6)
            network_map = dict()
            map_aux = dict()
            map_aux['ip6'] = list_ip

            network_map['ip6'] = map_aux

            # Business Rules

            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        '''Handles GET requests get an IP6 available.

        URL: ip/availableip6/ip_rede
        '''

        self.log.info('Get an IP6 available')

        try:
            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_network6 = kwargs.get('id_rede')

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

            # Business Rules

            ip6 = Ipv6.get_available_ip6(id_network6)

            list_ip = []
            list_ip.append(ip6)
            network_map = dict()
            map_aux = dict()
            map_aux['ip6'] = list_ip

            network_map['ip6'] = map_aux

            # Business Rules

            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Пример #17
0
def create_vip_request(vip_request, user):
    """
    Create Vip Request
    """
    # Remove when RequisicaoVips is die
    req = RequisicaoVips()
    req.save()

    vip = models.VipRequest()
    vip.id = req.id
    vip.name = vip_request['name']
    vip.service = vip_request['service']
    vip.business = vip_request['business']
    vip.environmentvip_id = vip_request['environmentvip']
    vip.ipv4 = Ip.get_by_pk(
        vip_request['ipv4']) if vip_request['ipv4'] else None
    vip.ipv6 = Ipv6.get_by_pk(
        vip_request['ipv6']) if vip_request['ipv6'] else None

    option_create = [
        vip_request['options'][key] for key in vip_request['options']
    ]
    vip.save()

    _create_port(vip_request['ports'], vip)
    _create_option(option_create, vip.id)

    # perms
    groups_perm = vip_request.get('groups_permissions', [])
    groups_perm += facade_usr.get_groups(
        vip_request.get('users_permissions', []))
    groups = facade_usr.reduce_groups(groups_perm)
    create_groups_permissions(groups, vip.id, user)

    # sync with old tables
    syncs.new_to_old(vip)

    return vip
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests for delete an IP6

        URL: ip6/delete/id_ip6
        """

        self.log.info('Delete an IP6')

        try:

            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations
            # Valid id access
            id_ip = kwargs.get('id_ipv6')

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

            ip = Ipv6.get_by_pk(id_ip)

            with distributedlock(LOCK_IPV6 % id_ip):

                locks_list = [LOCK_IPV6 % id_ip]
                # Business Rules
                ip.delete_v3(locks_list)

                return self.response(dumps_networkapi({}))

        except IpCantBeRemovedFromVip, e:
            return self.response_error(319, 'ip', 'ipv6', id_ip)
    def handle_get(self, request, user, *args, **kwargs):
        '''Handles GET requests for delete an IP6 

        URL: ip6/delete/id_ip6
        '''

        self.log.info('Delete an IP6')

        try:

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations
            # Valid id access
            id_ip = kwargs.get('id_ipv6')

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

            ip = Ipv6.get_by_pk(id_ip)

            with distributedlock(LOCK_IPV6 % id_ip):

                # Business Rules
                ip.delete()
                # Business Rules

                return self.response(dumps_networkapi({}))

        except IpCantBeRemovedFromVip, e:
            return self.response_error(319, "ip", 'ipv6', id_ip)
Пример #20
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4 and ipv6 of determined Equip.

        URLs: ip/getbyequip/id_equip
        """

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            # Business Rules
            listadeIps6 = []
            listaDeIps4 = []

            equip = Equipamento.get_by_pk(id_equip)

            ipEquip = IpEquipamento()
            ips = ipEquip.list_by_equip(equip.id)

            for ip4 in ips:
                listaDeIps4.append(Ip.get_by_pk(ip4.ip.id))

            ips = Ipv6Equipament.list_by_equip(equip.id)

            for ip6 in ips:
                listadeIps6.append(Ipv6.get_by_pk(ip6.ip.id))

            network_map = dict()

            list_ips = []
            list_ip4 = []
            list_ip6 = []

            dict_ips = dict()
            ip4_maps = dict()
            ip6_maps = dict()

            for ip4 in listaDeIps4:

                ip4_maps['id'] = ip4.id
                ip4_maps['oct1'] = ip4.oct1
                ip4_maps['oct2'] = ip4.oct2
                ip4_maps['oct3'] = ip4.oct3
                ip4_maps['oct4'] = ip4.oct4
                ip4_maps['descricao'] = ip4.descricao
                ip4_maps['id_rede'] = ip4.networkipv4_id
                list_ip4.append(ip4_maps)
                ip4_maps = dict()

            for ip6 in listadeIps6:

                ip6_maps['id'] = ip6.id
                ip6_maps['block1'] = ip6.block1
                ip6_maps['block2'] = ip6.block2
                ip6_maps['block3'] = ip6.block3
                ip6_maps['block4'] = ip6.block4
                ip6_maps['block5'] = ip6.block5
                ip6_maps['block6'] = ip6.block6
                ip6_maps['block7'] = ip6.block7
                ip6_maps['block8'] = ip6.block8
                ip6_maps['descricao'] = ip6.description
                ip6_maps['id_rede'] = ip6.networkipv6_id
                list_ip6.append(ip6_maps)
                ip6_maps = dict()

            dict_ips['ipv4'] = list_ip4
            dict_ips['ipv6'] = list_ip6
            list_ips.append(dict_ips)

            network_map['ips'] = list_ips

            # Return XML
            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            self.log.error(u'Parameter %s is invalid. Value: %s.', e.param,
                           e.value)
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Network

        URL: network/add/
        """

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # 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)
            network_map = networkapi_map.get('network')
            if network_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            network = network_map.get('network')
            id_vlan = network_map.get('id_vlan')
            network_type = network_map.get('id_network_type')
            environment_vip = network_map.get('id_environment_vip')

            # Valid Network
            try:
                net = IPNetwork(network)
            except ValueError, e:
                raise InvalidValueError(None, 'network', network)

            # VLAN

            # Valid vlan ID
            if not is_valid_int_greater_zero_param(id_vlan):
                raise InvalidValueError(None, 'id_vlan', id_vlan)

            # Find vlan by ID to check if it exist
            vlan = Vlan().get_by_pk(id_vlan)

            # Network Type

            # Valid network_type ID
            if not is_valid_int_greater_zero_param(network_type):
                raise InvalidValueError(None, 'id_network_type', network_type)

            # Find network_type by ID to check if it exist
            net_type = TipoRede.get_by_pk(network_type)

            # Environment Vip

            if environment_vip is not None:

                # Valid environment_vip ID
                if not is_valid_int_greater_zero_param(environment_vip):
                    raise InvalidValueError(
                        None, 'id_environment_vip', environment_vip)

                evips = EnvironmentVip.objects.all()

                evip_list = EnvironmentVip.available_evips(
                    EnvironmentVip(), evips, int(id_vlan))

                # Check if the chose environment is in the same environment
                if any(int(environment_vip) == item['id'] for item in evip_list):
                    # Find Environment VIP by ID to check if it exist
                    env_vip = EnvironmentVip.get_by_pk(environment_vip)
                else:
                    raise InvalidValueError(
                        None, 'id_environment_vip', environment_vip)

            else:
                env_vip = None

            # Check unchecked exception
            blocks, network, version = break_network(network)

            expl = split(
                net.network.exploded, "." if version == IP_VERSION.IPv4[0] else ":")
            expl.append(str(net.prefixlen))

            if blocks != expl:
                raise InvalidValueError(None, 'rede', network)

            # Business Rules

            if version == IP_VERSION.IPv4[0]:

                # Find all networks related to environment
                nets = NetworkIPv4.objects.select_related().filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([IPv4Network(
                    '%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets])

                # If network selected not in use
                if net in networks:
                    raise NetworkIPv4AddressNotAvailableError(
                        None, u'Unavailable address to create a NetworkIPv4.')

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv4.objects.select_related().filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([IPv4Network(
                        '%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    if net in networks:
                        raise NetworkIpAddressNotAvailableError(
                            None, u'Unavailable address to create a NetworkIPv4.')

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv4.objects.filter(
                    oct1=expl[0], oct2=expl[1], oct3=expl[2], oct4=expl[3], block=expl[4])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None, u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.')
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(filter=other_env_equips[0].ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None, u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.')

                # # Filter case 1 - end ##

                # New NetworkIPv4
                network_ip = NetworkIPv4()

                # Set octs by network generated
                network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str(
                    net.network).split('.')
                # Set block by network generated
                network_ip.block = net.prefixlen
                # Set mask by network generated
                network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = str(
                    net.netmask).split('.')
                # Set broadcast by network generated
                network_ip.broadcast = net.broadcast

            else:
                # Find all networks ralated to environment
                nets = NetworkIPv6.objects.select_related().filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3,
                                                                            net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets])

                # If network selected not in use
                if net in networks:
                    raise NetworkIPv6AddressNotAvailableError(
                        None, u'Unavailable address to create a NetworkIPv6.')

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv6.objects.select_related().filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (net_ip.block1, net_ip.block2, net_ip.block3,
                                                                                net_ip.block4, net_ip.block5, net_ip.block6, net_ip.block7, net_ip.block8, net_ip.block)) for net_ip in nets])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    if net in networks:
                        raise NetworkIpAddressNotAvailableError(
                            None, u'Unavailable address to create a NetworkIPv6.')

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv6.objects.filter(block1=expl[0], block2=expl[1], block3=expl[2], block4=expl[
                                                  3], block5=expl[4], block6=expl[5], block7=expl[6], block8=expl[7], block=expl[8])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None, u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.')
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(filter=other_env_equips[0].ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None, u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.')

                # # Filter case 1 - end ##

                # New NetworkIPv6
                network_ip = NetworkIPv6()

                # Set block by network generated
                network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, network_ip.block6, network_ip.block7, network_ip.block8 = str(
                    net.network.exploded).split(':')
                # Set block by network generated
                network_ip.block = net.prefixlen
                # Set mask by network generated
                network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, network_ip.mask6, network_ip.mask7, network_ip.mask8 = str(
                    net.netmask.exploded).split(':')

            # Get all vlans environments from equipments of the current
            # environment
            ambiente = vlan.ambiente

            equips = list()
            envs = list()
            envs_aux = list()

            for env in ambiente.equipamentoambiente_set.all():
                equips.append(env.equipamento)

            for equip in equips:
                for env in equip.equipamentoambiente_set.all():
                    if not env.ambiente_id in envs_aux:
                        envs.append(env.ambiente)
                        envs_aux.append(env.ambiente_id)

            # Check subnet's
            if version == IP_VERSION.IPv4[0]:
                expl = split(net.network.exploded, ".")
            else:
                expl = split(net.network.exploded, ":")

            expl.append(str(net.prefixlen))

            ids_exclude = []
            ids_all = []

            network_ip_verify = IPNetwork(network)
            for env in envs:
                for vlan_obj in env.vlan_set.all():
                    ids_all.append(vlan_obj.id)
                    is_subnet = verify_subnet(
                        vlan_obj, network_ip_verify, version)

                    if not is_subnet:
                        ids_exclude.append(vlan_obj.id)
                    else:
                        if ambiente.filter_id == None or vlan_obj.ambiente.filter_id == None or int(vlan_obj.ambiente.filter_id) != int(ambiente.filter_id):
                            pass
                        else:
                            ids_exclude.append(vlan_obj.id)

            # Ignore actual vlan
            if envs != [] and long(id_vlan) not in ids_exclude:
                ids_exclude.append(id_vlan)

            # Check if have duplicated vlan's with same net range in an
            # environment with shared equipment
            if len(ids_all) != len(ids_exclude):
                raise NetworkIPRangeEnvError(None)

            # Set Vlan
            network_ip.vlan = vlan

            # Set Network Type
            network_ip.network_type = net_type

            # Set Environment VIP
            network_ip.ambient_vip = env_vip

            # Persist
            try:

                # Delete vlan's cache
                destroy_cache_function([id_vlan])
                network_ip.save(user)

                list_equip_routers_ambient = EquipamentoAmbiente.objects.filter(
                    ambiente=network_ip.vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:

                    if version == IP_VERSION.IPv4[0]:

                        if network_ip.block < 31:

                            # Add Adds the first available ipv4 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ip = Ip.get_first_available_ip(network_ip.id)

                            ip = str(ip).split('.')

                            ip_model = Ip()
                            ip_model.oct1 = ip[0]
                            ip_model.oct2 = ip[1]
                            ip_model.oct3 = ip[2]
                            ip_model.oct4 = ip[3]
                            ip_model.networkipv4_id = network_ip.id

                            ip_model.save(user)

                            for equip in list_equip_routers_ambient:

                                IpEquipamento().create(
                                    user, ip_model.id, equip.equipamento.id)

                    else:
                        if network_ip.block < 127:

                            # Add Adds the first available ipv6 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ipv6 = Ipv6.get_first_available_ip6(network_ip.id)

                            ipv6 = str(ipv6).split(':')

                            ipv6_model = Ipv6()
                            ipv6_model.block1 = ipv6[0]
                            ipv6_model.block2 = ipv6[1]
                            ipv6_model.block3 = ipv6[2]
                            ipv6_model.block4 = ipv6[3]
                            ipv6_model.block5 = ipv6[4]
                            ipv6_model.block6 = ipv6[5]
                            ipv6_model.block7 = ipv6[6]
                            ipv6_model.block8 = ipv6[7]
                            ipv6_model.networkipv6_id = network_ip.id

                            ipv6_model.save(user)

                            for equip in list_equip_routers_ambient:

                                Ipv6Equipament().create(
                                    user, ipv6_model.id, equip.equipamento.id)

            except Exception, e:
                raise IpError(e, u'Error persisting Network.')
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Network

        URL: network/add/
        """

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # 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)
            network_map = networkapi_map.get('network')
            if network_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            network = network_map.get('network')
            id_vlan = network_map.get('id_vlan')
            network_type = network_map.get('id_network_type')
            environment_vip = network_map.get('id_environment_vip')
            cluster_unit = network_map.get('cluster_unit')

            # Valid Network
            try:
                net = IPNetwork(network)
            except ValueError, e:
                raise InvalidValueError(None, 'network', network)

            # VLAN

            # Valid vlan ID
            if not is_valid_int_greater_zero_param(id_vlan):
                raise InvalidValueError(None, 'id_vlan', id_vlan)

            # Find vlan by ID to check if it exist
            vlan = Vlan().get_by_pk(id_vlan)

            # Network Type

            # Valid network_type ID
            if not is_valid_int_greater_zero_param(network_type):
                raise InvalidValueError(None, 'id_network_type', network_type)

            # Find network_type by ID to check if it exist
            net_type = TipoRede.get_by_pk(network_type)

            # Environment Vip

            if environment_vip is not None:

                # Valid environment_vip ID
                if not is_valid_int_greater_zero_param(environment_vip):
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

                evips = EnvironmentVip.objects.all()

                evip_list = EnvironmentVip.available_evips(
                    EnvironmentVip(), evips, int(id_vlan))

                # Check if the chose environment is in the same environment
                if any(
                        int(environment_vip) == item['id']
                        for item in evip_list):
                    # Find Environment VIP by ID to check if it exist
                    env_vip = EnvironmentVip.get_by_pk(environment_vip)
                else:
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

            else:
                env_vip = None

            # Check unchecked exception
            blocks, network, version = break_network(network)

            expl = split(net.network.exploded,
                         '.' if version == IP_VERSION.IPv4[0] else ':')
            expl.append(str(net.prefixlen))

            if blocks != expl:
                raise InvalidValueError(None, 'rede', network)

            # Business Rules

            if version == IP_VERSION.IPv4[0]:

                # Find all networks related to environment
                nets = NetworkIPv4.objects.filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([
                    IPv4Network('%d.%d.%d.%d/%d' %
                                (net_ip.oct1, net_ip.oct2, net_ip.oct3,
                                 net_ip.oct4, net_ip.block)) for net_ip in nets
                ])

                # If network selected not in use
                for network_aux in networks:
                    if net in network_aux or network_aux in net:
                        self.log.debug(
                            'Network %s cannot be allocated. It conflicts with %s already in use in this environment.'
                            % (net, network))
                        raise NetworkIPv4AddressNotAvailableError(
                            None,
                            u'Network cannot be allocated. %s already in use in this environment.'
                            % network_aux)

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv4.objects.filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([
                        IPv4Network('%d.%d.%d.%d/%d' %
                                    (net_ip.oct1, net_ip.oct2, net_ip.oct3,
                                     net_ip.oct4, net_ip.block))
                        for net_ip in nets
                    ])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    for network_aux in networks:
                        if net in network_aux or network_aux in net:
                            self.log.debug(
                                'Network %s cannot be allocated. It conflicts with %s already in use in this environment VIP.'
                                % (net, network))
                            raise NetworkIPv4AddressNotAvailableError(
                                None,
                                u'Network cannot be allocated. %s already in use in this environment VIP.'
                                % network_aux)

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv4.objects.filter(oct1=expl[0],
                                                  oct2=expl[1],
                                                  oct3=expl[2],
                                                  oct4=expl[3],
                                                  block=expl[4])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[
                                        0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None,
                                        u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.'
                                    )
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=other_env_equips[0].
                                            ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None,
                                            u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.'
                                        )

                # # Filter case 1 - end ##

                # New NetworkIPv4
                network_ip = NetworkIPv4()

                # Set octs by network generated
                network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str(
                    net.network).split('.')
                # Set block by network generated
                network_ip.block = net.prefixlen
                # Set mask by network generated
                network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = str(
                    net.netmask).split('.')
                # Set broadcast by network generated
                network_ip.broadcast = net.broadcast.compressed

            else:
                # Find all networks ralated to environment
                nets = NetworkIPv6.objects.filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([
                    IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' %
                                (net_ip.block1, net_ip.block2, net_ip.block3,
                                 net_ip.block4, net_ip.block5, net_ip.block6,
                                 net_ip.block7, net_ip.block8, net_ip.block))
                    for net_ip in nets
                ])

                # If network selected not in use
                for network_aux in networks:
                    if net in network_aux or network_aux in net:
                        self.log.debug(
                            'Network %s cannot be allocated. It conflicts with %s already in use in this environment.'
                            % (net, network))
                        raise NetworkIPv4AddressNotAvailableError(
                            None,
                            u'Network cannot be allocated. %s already in use in this environment.'
                            % network_aux)

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv6.objects.filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([
                        IPv6Network(
                            '%s:%s:%s:%s:%s:%s:%s:%s/%d' %
                            (net_ip.block1, net_ip.block2, net_ip.block3,
                             net_ip.block4, net_ip.block5, net_ip.block6,
                             net_ip.block7, net_ip.block8, net_ip.block))
                        for net_ip in nets
                    ])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    for network_aux in networks:
                        if net in network_aux or network_aux in net:
                            self.log.debug(
                                'Network %s cannot be allocated. It conflicts with %s already in use in this environment VIP.'
                                % (net, network))
                            raise NetworkIPv4AddressNotAvailableError(
                                None,
                                u'Network cannot be allocated. %s already in use in this environment VIP.'
                                % network_aux)

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv6.objects.filter(block1=expl[0],
                                                  block2=expl[1],
                                                  block3=expl[2],
                                                  block4=expl[3],
                                                  block5=expl[4],
                                                  block6=expl[5],
                                                  block7=expl[6],
                                                  block8=expl[7],
                                                  block=expl[8])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[
                                        0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None,
                                        u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.'
                                    )
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=other_env_equips[0].
                                            ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None,
                                            u'Um dos equipamentos associados com o ambiente desta rede também está associado com outro ambiente que tem uma rede com essa mesma faixa, adicione filtros nos ambientes se necessário.'
                                        )

                # # Filter case 1 - end ##

                # New NetworkIPv6
                network_ip = NetworkIPv6()

                # Set block by network generated
                network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, network_ip.block6, network_ip.block7, network_ip.block8 = str(
                    net.network.exploded).split(':')
                # Set block by network generated
                network_ip.block = net.prefixlen
                # Set mask by network generated
                network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, network_ip.mask6, network_ip.mask7, network_ip.mask8 = str(
                    net.netmask.exploded).split(':')

            # Get all vlans environments from equipments of the current
            # environment
            ambiente = vlan.ambiente

            equips = list()
            envs = list()

            # equips = all equipments from the environment which this network
            # is about to be allocated on
            for env in ambiente.equipamentoambiente_set.all():
                equips.append(env.equipamento)

            # envs = all environments from all equips above
            # This will be used to test all networks from the environments.
            for equip in equips:
                for env in equip.equipamentoambiente_set.all():
                    if env.ambiente not in envs:
                        envs.append(env.ambiente)

            network_ip_verify = IPNetwork(network)
            # For all vlans in all common environments,
            # check if any network is a subnetwork or supernetwork
            # of the desired network network_ip_verify
            for env in envs:
                for vlan_obj in env.vlan_set.all():
                    is_subnet = verify_subnet(vlan_obj, network_ip_verify,
                                              version)

                    if is_subnet:
                        if vlan_obj.ambiente == ambiente:
                            raise NetworkIPRangeEnvError(None)

                        if ambiente.filter_id is None or vlan_obj.ambiente.filter_id is None or int(
                                vlan_obj.ambiente.filter_id) != int(
                                    ambiente.filter_id):
                            raise NetworkIPRangeEnvError(None)

            # Set Vlan
            network_ip.vlan = vlan

            # Set Network Type
            network_ip.network_type = net_type

            # Set Environment VIP
            network_ip.ambient_vip = env_vip

            # Set Cluster Unit
            network_ip.cluster_unit = cluster_unit

            # Persist
            try:

                # Delete vlan's cache
                destroy_cache_function([id_vlan])
                network_ip.save()

                list_equip_routers_ambient = EquipamentoAmbiente.objects.filter(
                    ambiente=network_ip.vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:

                    if version == IP_VERSION.IPv4[0]:

                        if network_ip.block < 31:

                            # Add Adds the first available ipv4 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ip = Ip.get_first_available_ip(network_ip.id)

                            ip = str(ip).split('.')

                            ip_model = Ip()
                            ip_model.oct1 = ip[0]
                            ip_model.oct2 = ip[1]
                            ip_model.oct3 = ip[2]
                            ip_model.oct4 = ip[3]
                            ip_model.networkipv4_id = network_ip.id

                            ip_model.save()

                            if len(list_equip_routers_ambient
                                   ) > 1 and network_ip.block < 30:
                                multiple_ips = True
                            else:
                                multiple_ips = False

                            for equip in list_equip_routers_ambient:
                                IpEquipamento().create(user, ip_model.id,
                                                       equip.equipamento.id)

                                if multiple_ips:
                                    router_ip = Ip.get_first_available_ip(
                                        network_ip.id, True)
                                    router_ip = str(router_ip).split('.')
                                    ip_model2 = Ip()
                                    ip_model2.oct1 = router_ip[0]
                                    ip_model2.oct2 = router_ip[1]
                                    ip_model2.oct3 = router_ip[2]
                                    ip_model2.oct4 = router_ip[3]
                                    ip_model2.networkipv4_id = network_ip.id
                                    ip_model2.save(user)
                                    IpEquipamento().create(
                                        user, ip_model2.id,
                                        equip.equipamento.id)

                    else:
                        if network_ip.block < 127:

                            # Add Adds the first available ipv6 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ipv6 = Ipv6.get_first_available_ip6(network_ip.id)

                            ipv6 = str(ipv6).split(':')

                            ipv6_model = Ipv6()
                            ipv6_model.block1 = ipv6[0]
                            ipv6_model.block2 = ipv6[1]
                            ipv6_model.block3 = ipv6[2]
                            ipv6_model.block4 = ipv6[3]
                            ipv6_model.block5 = ipv6[4]
                            ipv6_model.block6 = ipv6[5]
                            ipv6_model.block7 = ipv6[6]
                            ipv6_model.block8 = ipv6[7]
                            ipv6_model.networkipv6_id = network_ip.id

                            ipv6_model.save()

                            if len(list_equip_routers_ambient
                                   ) > 1 and network_ip.block < 126:
                                multiple_ips = True
                            else:
                                multiple_ips = False

                            for equip in list_equip_routers_ambient:
                                Ipv6Equipament().create(
                                    user, ipv6_model.id, equip.equipamento.id)

                                if multiple_ips:
                                    router_ip = Ipv6.get_first_available_ip6(
                                        network_ip.id, True)
                                    router_ip = str(router_ip).split(':')
                                    ipv6_model2 = Ipv6()
                                    ipv6_model2.block1 = router_ip[0]
                                    ipv6_model2.block2 = router_ip[1]
                                    ipv6_model2.block3 = router_ip[2]
                                    ipv6_model2.block4 = router_ip[3]
                                    ipv6_model2.block5 = router_ip[4]
                                    ipv6_model2.block6 = router_ip[5]
                                    ipv6_model2.block7 = router_ip[6]
                                    ipv6_model2.block8 = router_ip[7]
                                    ipv6_model2.networkipv6_id = network_ip.id
                                    ipv6_model2.save(user)
                                    Ipv6Equipament().create(
                                        user, ipv6_model2.id,
                                        equip.equipamento.id)

            except Exception, e:
                raise IpError(e, u'Error persisting Network.')
Пример #23
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to get an IPv4 or Ipv6 by oct or blocks .

        URL: ip/getbyoctblock/
        """

        self.log.info("Get a Ipv4's or Ipv6's")

        try:

            # Business Validations

            # 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
            ip = ip_map.get('ip')

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

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

            # Business Rules
            version = ''
            ip_list = ip.split('.')

            if len(ip_list) == 1:

                ip_list = ip.split(':')
                ips = Ipv6.get_by_blocks(ip_list[0], ip_list[1], ip_list[2], ip_list[
                                         3], ip_list[4], ip_list[5], ip_list[6], ip_list[7])
                version = IP_VERSION.IPv6[1]

            else:

                ips = Ip.get_by_octs(
                    ip_list[0], ip_list[1], ip_list[2], ip_list[3])
                version = IP_VERSION.IPv4[1]

            ips_list = []
            for ip in ips:
                ip_dict = model_to_dict(ip)
                ip_dict['version'] = version
                ips_list.append(ip_dict)

            return self.response(dumps_networkapi({'ips': ips_list}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
Пример #24
0
def prepare_apply(load_balance, vip, created=True, user=None):

    vip_request = copy.deepcopy(vip)

    id_vip = str(vip_request.get('id'))

    equips, conf, cluster_unit = _validate_vip_to_apply(
        vip_request, created, user)

    cache_group = OptionVip.objects.get(
        id=vip_request.get('options').get('cache_group'))
    traffic_return = OptionVip.objects.get(
        id=vip_request.get('options').get('traffic_return'))
    timeout = OptionVip.objects.get(
        id=vip_request.get('options').get('timeout'))
    persistence = OptionVip.objects.get(
        id=vip_request.get('options').get('persistence'))

    if vip_request['ipv4']:
        ipv4 = Ip.get_by_pk(vip_request['ipv4']) if vip_request[
            'ipv4'] else None
        vip_request['ipv4'] = {
            'id': ipv4.id,
            'ip_formated': ipv4.ip_formated
        }

    if vip_request['ipv6']:
        ipv6 = Ipv6.get_by_pk(vip_request['ipv6']) if vip_request[
            'ipv6'] else None
        vip_request['ipv6'] = {
            'id': ipv6.id,
            'ip_formated': ipv6.ip_formated
        }

    if conf:
        conf = json.loads(conf)

    vip_request['options'] = dict()
    vip_request['options']['cache_group'] = {
        'id': cache_group.id,
        'nome_opcao_txt': cache_group.nome_opcao_txt
    }
    vip_request['options']['traffic_return'] = {
        'id': traffic_return.id,
        'nome_opcao_txt': traffic_return.nome_opcao_txt
    }
    vip_request['options']['timeout'] = {
        'id': timeout.id,
        'nome_opcao_txt': timeout.nome_opcao_txt
    }
    vip_request['options']['persistence'] = {
        'id': persistence.id,
        'nome_opcao_txt': persistence.nome_opcao_txt
    }
    vip_request['options']['cluster_unit'] = cluster_unit

    try:
        vip_request['options']['dscp'] = VipRequestDSCP.objects.get(
            vip_request=vip_request['id']
        ).dscp
    except:
        vip_request['options']['dscp'] = None
        pass

    for idx, port in enumerate(vip_request['ports']):
        for i, pl in enumerate(port['pools']):

            pool = get_pool_by_id(pl['server_pool'])
            pool_serializer = pool_slz.PoolV3Serializer(pool)

            l7_rule = OptionVip.objects.get(
                id=pl['l7_rule']).nome_opcao_txt

            healthcheck = pool_serializer.data['healthcheck']
            healthcheck['identifier'] = reserve_name_healthcheck(
                pool_serializer.data['identifier'])
            healthcheck['new'] = True
            vip_request['ports'][idx]['pools'][i]['server_pool'] = {
                'id': pool_serializer.data['id'],
                'nome': pool_serializer.data['identifier'],
                'lb_method': pool_serializer.data['lb_method'],
                'healthcheck': healthcheck,
                'action': pool_serializer.data['servicedownaction']['name'],
                'pool_created': pool_serializer.data['pool_created'],
                'pools_members': [{
                    'id': pool_member['id'],
                    'identifier': pool_member['identifier'],
                    'ip': pool_member['ip']['ip_formated'] if pool_member['ip'] else pool_member['ipv6']['ip_formated'],
                    'port': pool_member['port_real'],
                    'member_status': pool_member['member_status'],
                    'limit': pool_member['limit'],
                    'priority': pool_member['priority'],
                    'weight': pool_member['weight']
                } for pool_member in pool_serializer.data['server_pool_members']]
            }

            vip_request['ports'][idx]['pools'][i]['l7_rule'] = l7_rule
        l7_protocol = OptionVip.objects.get(
            id=port['options']['l7_protocol'])
        l4_protocol = OptionVip.objects.get(
            id=port['options']['l4_protocol'])

        vip_request['ports'][idx]['options'] = dict()
        vip_request['ports'][idx]['options']['l7_protocol'] = {
            'id': l7_protocol.id,
            'nome_opcao_txt': l7_protocol.nome_opcao_txt
        }
        vip_request['ports'][idx]['options']['l4_protocol'] = {
            'id': l4_protocol.id,
            'nome_opcao_txt': l4_protocol.nome_opcao_txt
        }

    vip_request['conf'] = conf

    if conf:
        for idx, layer in enumerate(conf['conf']['layers']):
            requiments = layer.get('requiments')
            if requiments:
                # validate for port
                for idx_port, port in enumerate(vip['ports']):
                    for requiment in requiments:
                        condicionals = requiment.get('condicionals')
                        for condicional in condicionals:

                            validated = True

                            validations = condicional.get('validations')
                            for validation in validations:
                                if validation.get('type') == 'optionvip':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        int(vip['options'][
                                            validation.get('variable')]),
                                        int(validation.get('value'))
                                    )

                                if validation.get('type') == 'portoptionvip':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        int(port['options'][
                                            validation.get('variable')]),
                                        int(validation.get('value'))
                                    )

                                if validation.get('type') == 'field' and validation.get('variable') == 'cluster_unit':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        cluster_unit,
                                        validation.get('value')
                                    )
                            if validated:
                                use = condicional.get('use')
                                for item in use:
                                    definitions = item.get('definitions')
                                    eqpts = item.get('eqpts')
                                    if eqpts:

                                        eqpts = Equipamento.objects.filter(
                                            id__in=eqpts,
                                            maintenance=0,
                                            tipo_equipamento__tipo_equipamento=u'Balanceador').distinct()

                                        if facade_eqpt.all_equipments_are_in_maintenance(equips):
                                            raise exceptions_eqpt.AllEquipmentsAreInMaintenanceException()

                                        if user:
                                            if not facade_eqpt.all_equipments_can_update_config(equips, user):
                                                raise exceptions_eqpt.UserDoesNotHavePermInAllEqptException(
                                                    'User does not have permission to update conf in eqpt. \
                                                    Verify the permissions of user group with equipment group. Vip:{}'.format(
                                                        vip_request['id']))

                                        for eqpt in eqpts:
                                            eqpt_id = str(eqpt.id)

                                            if not load_balance.get(eqpt_id):
                                                equipment_access = EquipamentoAcesso.search(
                                                    equipamento=eqpt.id
                                                )

                                                plugin = PluginFactory.factory(
                                                    eqpt)

                                                load_balance[eqpt_id] = {
                                                    'plugin': plugin,
                                                    'access': equipment_access,
                                                    'vips': [],
                                                    'layers': {},
                                                }

                                            idx_layer = str(idx)
                                            idx_port_str = str(port['port'])
                                            if not load_balance[eqpt_id]['layers'].get(id_vip):
                                                load_balance[eqpt_id][
                                                    'layers'][id_vip] = dict()

                                            if load_balance[eqpt_id]['layers'][id_vip].get(idx_layer):
                                                if load_balance[eqpt_id]['layers'][id_vip].get(idx_layer).get('definitions').get(idx_port_str):
                                                    load_balance[eqpt_id]['layers'][id_vip][idx_layer][
                                                        'definitions'][idx_port_str] += definitions
                                                else:
                                                    load_balance[eqpt_id]['layers'][id_vip][idx_layer][
                                                        'definitions'][idx_port_str] = definitions
                                            else:
                                                load_balance[eqpt_id]['layers'][id_vip][idx_layer] = {
                                                    'vip_request': vip_request,
                                                    'definitions': {
                                                        idx_port_str: definitions
                                                    }
                                                }
                                # In first validated==True stops conditionals.
                                # Removing this break will add a wrong
                                # conditional.
                                break

    for e in equips:
        eqpt_id = str(e.id)

        if not load_balance.get(eqpt_id):

            equipment_access = EquipamentoAcesso.search(
                equipamento=e.id
            )

            plugin = PluginFactory.factory(e)

            load_balance[eqpt_id] = {
                'plugin': plugin,
                'access': equipment_access,
                'vips': [],
                'layers': {},
            }

        load_balance[eqpt_id]['vips'].append({'vip_request': vip_request})

    return load_balance
Пример #25
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
Пример #26
0
    def handle_put(self, request, user, *args, **kwargs):
        """
        Handles PUT requests to change the VIP's real server.

        URL: vip/real/edit
        """

        self.log.info("Change VIP's real server")

        try:

            # User permission
            if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Commons Validations

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data,
                ['real', 'reals_weight', 'reals_priority'])

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

            vip_map = networkapi_map.get('vip')
            if vip_map is None:
                return self.response_error(
                    3, u'There is no value to the vip tag  of XML request.')

            # Get XML data
            vip_id = vip_map.get('vip_id')
            alter_priority = vip_map.get('alter_priority')

            # Valid VIP ID
            if not is_valid_int_greater_zero_param(vip_id):
                self.log.error(
                    u'The vip_id parameter is not a valid value: %s.', vip_id)
                raise InvalidValueError(None, 'vip_id', vip_id)

            # Valid Alter Priority
            if not is_valid_int_greater_equal_zero_param(alter_priority):
                alter_priority = 0

            # Existing Vip ID
            vip = RequisicaoVips.get_by_pk(vip_id)

            # Clone vip
            vip_old = clone(vip)

            server_pools = ServerPool.objects.filter(
                vipporttopool__requisicao_vip=vip)
            server_pools_old = []
            server_pools_members_old = []
            for sp in server_pools:
                server_pools_old.append(sp)
                for spm in sp.serverpoolmember_set.all():
                    server_pools_members_old.append(spm)

            # Get variables
            variables_map = vip.variables_to_map()

            # Valid variables
            vip.set_variables(variables_map)

            # Get balancing method
            vip_map['metodo_bal'] = str(
                variables_map.get('metodo_bal')).upper()

            with distributedlock(LOCK_VIP % vip_id):

                # Valid real names and real ips of real server
                if vip_map.get('reals') is not None:

                    evip = EnvironmentVip.get_by_values(
                        variables_map.get('finalidade'),
                        variables_map.get('cliente'),
                        variables_map.get('ambiente'))

                    for real in vip_map.get('reals').get('real'):
                        ip_aux_error = real.get('real_ip')
                        equip_aux_error = real.get('real_name')
                        if equip_aux_error is not None:
                            equip = Equipamento.get_by_name(equip_aux_error)
                        else:
                            self.log.error(
                                u'The real_name parameter is not a valid value: None.'
                            )
                            raise InvalidValueError(None, 'real_name', 'None')

                        # Valid Real
                        RequisicaoVips.valid_real_server(
                            ip_aux_error, equip, evip, False)

                    # Valid reals_prioritys
                    vip_map, code = vip.valid_values_reals_priority(vip_map)
                    if code is not None:
                        return self.response_error(329)

                    # Valid reals_weight
                    vip_map, code = vip.valid_values_reals_weight(vip_map)
                    if code is not None:
                        return self.response_error(330)

                # Get variables
                variables_map = vip.variables_to_map()

                vip_port_list, reals_list, reals_priority, reals_weight = vip.get_vips_and_reals(
                    vip.id)

                if reals_list:
                    variables_map['reals'] = {'real': reals_list}
                    variables_map['reals_prioritys'] = {
                        'reals_priority': reals_priority
                    }
                    variables_map['reals_weights'] = {
                        'reals_weight': reals_weight
                    }

                variables_map['portas_servicos'] = {'porta': vip_port_list}

                # clone variables_map
                # variables_map_old = clone(variables_map)

                # Valid ports
                variables_map, code = vip.valid_values_ports(variables_map)
                if code is not None:
                    return self.response_error(331)
                """ OLD CALLS - Deprecated """
                vip_ports_pool = VipPortToPool.objects.filter(
                    requisicao_vip=vip)

                reals = vip_map.get('reals')

                new_call = True
                if reals and 'port_real' not in reals['real'][0]:
                    new_call = False
                    reals_prioritys = vip_map.get('reals_prioritys')
                    reals_weights = dict()
                    if 'reals_weights' in vip_map:
                        reals_weights = vip_map.get('reals_weights')

                    reals_aux = dict()
                    reals_prioritys_aux = dict()
                    reals_weight_aux = dict()

                    reals_aux['real'] = list()
                    reals_prioritys_aux['reals_priority'] = list()
                    reals_weight_aux['reals_weight'] = list()

                    repeat = (len(vip_ports_pool) * len(reals['real'])) / len(
                        reals['real'])
                    execute_list = list()

                    for x in range(repeat):
                        execute_list.append((x + 1) * len(reals['real']))

                    for i in range(len(reals['real'])):
                        for vippp in vip_ports_pool:

                            reals_prioritys_aux['reals_priority'].append(
                                reals_prioritys['reals_priority'][i])
                            if 'reals_weight' in reals_weights:
                                reals_weight_aux['reals_weight'].append(
                                    reals_weights['reals_weight'][i])
                            server_pool = ServerPool.objects.get(
                                vipporttopool__id=vippp.id,
                                vipporttopool__requisicao_vip=vip)

                            if 'id_ip' not in reals['real'][i]:
                                id_ip = get_id_ip(reals['real'][i])
                            else:
                                id_ip = reals['real'][i]['id_ip']

                            reals_aux['real'].append({
                                'id_ip':
                                id_ip,
                                'port_real':
                                server_pool.default_port,
                                'real_name':
                                reals['real'][i]['real_name'],
                                'port_vip':
                                vippp.port_vip,
                                u'real_ip':
                                reals['real'][i]['real_ip']
                            })

                        vip_map['reals_prioritys'] = reals_prioritys_aux
                        vip_map['reals_weights'] = reals_weight_aux
                        vip_map['reals'] = reals_aux
                """ OLD CALLS - END """

                # Check diff reals (reals_to_add, reals_to_rem, reals_to_stay)
                reals_to_add, reals_to_rem, reals_to_stay = diff_reals(
                    variables_map, vip_map)

                reals_final = dict()
                reals_final['reals'] = list()
                reals_final['priorities'] = list()
                reals_final['weights'] = list()

                reals_error = list()
                removes = True
                error = False

                ##############################################
                #        NOT MODIFIED - reals_to_stay        #
                ##############################################
                for i in range(len(reals_to_stay['reals'])):

                    real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables(
                        reals_to_stay, i, new_call)

                    # Check ip type
                    if is_valid_ipv4(real.get('real_ip')) is True:
                        ip_type = IP_VERSION.IPv4[1]
                        ip = Ip().get_by_pk(id_ip)
                    else:
                        ip_type = IP_VERSION.IPv6[1]
                        ip = Ipv6().get_by_pk(id_ip)

                    reals_final['reals'].append(reals_to_stay['reals'][i])
                    reals_final['priorities'].append(
                        reals_to_stay['priorities'][i])
                    if reals_to_stay['weighted']:
                        reals_final['weights'].append(
                            reals_to_stay['weights'][i])

                        server_pool = ServerPool.objects.get(
                            vipporttopool__port_vip=port_vip,
                            vipporttopool__requisicao_vip=vip)
                        if ip_type == IP_VERSION.IPv4[1]:
                            server_pool_member = ServerPoolMember.objects.get(
                                server_pool=server_pool,
                                port_real=port_real,
                                ip=id_ip)
                        else:
                            server_pool_member = ServerPoolMember.objects.get(
                                server_pool=server_pool,
                                port_real=port_real,
                                ipv6=id_ip)
                    server_pool_member.priority = priority
                    server_pool_member.weight = weight
                    server_pool_member.save(user, commit=True)

                #############################################
                #          ADD REALS - reals_to_add         #
                #############################################
                for i in range(len(reals_to_add['reals'])):

                    real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables(
                        reals_to_add, i, new_call)

                    if len(real.get('real_ip').split('.')) <= 1:
                        ip_type = IP_VERSION.IPv6[1]
                        ip = Ipv6().get_by_pk(id_ip)
                        if new_call:
                            command = VIP_REALS_v6_CREATE % (
                                vip.id, id_ip, port_real, port_vip)
                        else:
                            command = VIP_REAL_v6_CREATE % (
                                vip.id, real.get('real_name'),
                                real.get('real_ip'))
                    else:
                        ip_type = IP_VERSION.IPv4[1]
                        ip = Ip().get_by_pk(id_ip)
                        if new_call:
                            command = VIP_REALS_v4_CREATE % (
                                vip.id, id_ip, port_real, port_vip)
                        else:
                            command = VIP_REAL_v4_CREATE % (
                                vip.id, real.get('real_name'),
                                real.get('real_ip'))

                    self.log.info(
                        '------------------- ADD ----------------------')
                    self.log.info(
                        'Insert ServerPoolMember before execute script')

                    add_reals_before_script(port_vip, vip, ip, ip_type,
                                            priority, weight, port_real, user)

                    self.log.info('The insert has completed successfully')

                    # if new_call or (i + 1) in execute_list:

                    self.log.info('Execute script: %s' % command)

                    code, stdout, stderr = exec_script(command)

                    self.log.info('Script was executed and returned code %s' %
                                  code)

                    if code != 0:
                        removes = False
                        error = True
                        reals_error.append(real)

                        self.log.info(
                            'Remove ServerPoolMember after execute script if code != 0'
                        )
                        remove_reals_after_script(port_vip, ip_type, vip,
                                                  port_real, priority, weight,
                                                  id_ip, user)
                        self.log.info('The remove has completed successfully')

                    else:
                        reals_final['reals'].append(real)
                        reals_final['priorities'].append(
                            reals_to_add['priorities'][i])
                        if reals_to_add['weighted']:
                            reals_final['weights'].append(
                                reals_to_add['weights'][i])

                    self.log.info(
                        '----------------- ADD END --------------------')

                ##########################################
                #       REMOVE REALS - reals_to_rem      #
                ##########################################
                if removes:
                    for i in range(len(reals_to_rem['reals'])):

                        real, priority, weight, id_ip, port_vip, port_real, new_call = get_variables(
                            reals_to_rem, i, new_call)

                        if len(real.get('real_ip').split('.')) <= 1:
                            ip_type = IP_VERSION.IPv6[1]
                            if new_call:
                                command = VIP_REALS_v6_REMOVE % (
                                    vip.id, id_ip, port_real, port_vip)
                            else:
                                command = VIP_REAL_v6_REMOVE % (
                                    vip.id, real.get('real_name'),
                                    real.get('real_ip'))
                        else:
                            ip_type = IP_VERSION.IPv4[1]
                            if new_call:
                                command = VIP_REALS_v4_REMOVE % (
                                    vip.id, id_ip, port_real, port_vip)
                            else:
                                command = VIP_REAL_v4_REMOVE % (
                                    vip.id, real.get('real_name'),
                                    real.get('real_ip'))

                        self.log.info(
                            '------------------ REMOVE --------------------')
                        self.log.info('Execute script: %s' % command)

                        code, stdout, stderr = exec_script(command)

                        self.log.info(
                            'script was executed and returned code %s' % code)

                        if code != 0:
                            error = True
                            reals_error.append(real)
                            reals_final['reals'].append(real)
                            reals_final['priorities'].append(
                                reals_to_rem['priorities'][i])
                            if reals_to_rem['weighted']:
                                reals_final['weights'].append(
                                    reals_to_rem['weights'][i])
                        else:

                            self.log.info(
                                'Remove ServerPoolMember after execute script')
                            remove_reals_after_script(port_vip, ip_type, vip,
                                                      port_real, priority,
                                                      weight, id_ip, user)
                            self.log.info(
                                'The remove has completed successfully')

                        self.log.info(
                            '---------------- REMOVE END ------------------')

                else:
                    for i in range(len(reals_to_rem['reals'])):
                        real = reals_to_rem['reals'][i]
                        reals_final['reals'].append(real)
                        reals_final['priorities'].append(
                            reals_to_rem['priorities'][i])
                        if reals_to_add['weighted']:
                            reals_final['weights'].append(
                                reals_to_rem['weights'][i])

                variables_map['reals'] = dict()
                variables_map['reals_prioritys'] = dict()
                variables_map['reals_weights'] = dict()

                if len(reals_final['reals']) > 0:
                    variables_map['reals']['real'] = reals_final['reals']
                    variables_map['reals_prioritys'][
                        'reals_priority'] = reals_final['priorities']
                    if reals_final['weights'] is not None:
                        variables_map['reals_weights'][
                            'reals_weight'] = reals_final['weights']
                else:
                    variables_map.pop('reals')
                    variables_map.pop('reals_prioritys')
                    variables_map.pop('reals_weights')

                # set variables
                vip.set_variables(variables_map)

                try:
                    # If Priority changed
                    if int(alter_priority) != 0:
                        # gerador_vips -i <ID_REQUISICAO> --priority
                        command = 'gerador_vips -i %d --priority' % vip.id

                        # Logging
                        self.log.info(
                            '---------------- ALTER PRIORITY ------------------'
                        )
                        self.log.info('Command: ' + command)

                        # Execute script
                        code, stdout, stderr = exec_script(command)
                        self.log.info('Code returned: ' + str(code))
                        self.log.info('Stdout: ' + stdout)
                        self.log.info(
                            '-------------- ALTER PRIORITY END ----------------'
                        )

                        # Script returned error while executing, rollback the
                        # changes in database
                        if code != 0:
                            self.log.info('Code != 0, rollback changes')
                            vip_old.save(user, commit=True)
                            for sp in server_pools_old:
                                sp.save(user, commit=True)
                            for spm in server_pools_members_old:
                                spm.save(user, commit=True)

                            return self.response_error(2, stdout + stderr)

                except Exception, e:
                    if isinstance(e, IntegrityError):
                        # Duplicate value for Port Vip, Port Real and IP
                        self.log.error(u'Failed to update the request vip.')
                        return self.response_error(353)
                    else:
                        self.log.error(u'Failed to update the request vip.')
                        raise RequisicaoVipsError(
                            e, u'Failed to update the request vip')

                if error:
                    # build return message
                    vip_list = ''
                    ip_list = ''

                    for real in reals_error:
                        vip_list = vip_list + real['real_name'] + ', '
                        ip_list = ip_list + real['real_ip'] + ', '

                    return self.response_error(333, vip_list[:-2],
                                               ip_list[:-2])
                else:
                    return self.response(dumps_networkapi({}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
Пример #27
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
Пример #28
0
def prepare_apply(load_balance, vip, created=True, user=None):

    vip_request = copy.deepcopy(vip)

    id_vip = str(vip_request.get('id'))

    equips, conf, cluster_unit = _validate_vip_to_apply(
        vip_request, created, user)

    cache_group = OptionVip.objects.get(
        id=vip_request.get('options').get('cache_group'))
    traffic_return = OptionVip.objects.get(
        id=vip_request.get('options').get('traffic_return'))
    timeout = OptionVip.objects.get(
        id=vip_request.get('options').get('timeout'))
    persistence = OptionVip.objects.get(
        id=vip_request.get('options').get('persistence'))

    if vip_request['ipv4']:
        ipv4 = Ip.get_by_pk(
            vip_request['ipv4']) if vip_request['ipv4'] else None
        vip_request['ipv4'] = {'id': ipv4.id, 'ip_formated': ipv4.ip_formated}

    if vip_request['ipv6']:
        ipv6 = Ipv6.get_by_pk(
            vip_request['ipv6']) if vip_request['ipv6'] else None
        vip_request['ipv6'] = {'id': ipv6.id, 'ip_formated': ipv6.ip_formated}

    if conf:
        conf = json.loads(conf)

    vip_request['options'] = dict()
    vip_request['options']['cache_group'] = {
        'id': cache_group.id,
        'nome_opcao_txt': cache_group.nome_opcao_txt
    }
    vip_request['options']['traffic_return'] = {
        'id': traffic_return.id,
        'nome_opcao_txt': traffic_return.nome_opcao_txt
    }
    vip_request['options']['timeout'] = {
        'id': timeout.id,
        'nome_opcao_txt': timeout.nome_opcao_txt
    }
    vip_request['options']['persistence'] = {
        'id': persistence.id,
        'nome_opcao_txt': persistence.nome_opcao_txt
    }
    vip_request['options']['cluster_unit'] = cluster_unit

    try:
        vip_request['options']['dscp'] = VipRequestDSCP.objects.get(
            vip_request=vip_request['id']).dscp
    except:
        vip_request['options']['dscp'] = None
        pass

    for idx, port in enumerate(vip_request['ports']):
        for i, pl in enumerate(port['pools']):

            pool = get_pool_by_id(pl['server_pool'])
            pool_serializer = pool_slz.PoolV3Serializer(pool)

            l7_rule = OptionVip.objects.get(id=pl['l7_rule']).nome_opcao_txt

            healthcheck = pool_serializer.data['healthcheck']
            healthcheck['identifier'] = reserve_name_healthcheck(
                pool_serializer.data['identifier'])
            healthcheck['new'] = True
            vip_request['ports'][idx]['pools'][i]['server_pool'] = {
                'id':
                pool_serializer.data['id'],
                'nome':
                pool_serializer.data['identifier'],
                'lb_method':
                pool_serializer.data['lb_method'],
                'healthcheck':
                healthcheck,
                'action':
                pool_serializer.data['servicedownaction']['name'],
                'pool_created':
                pool_serializer.data['pool_created'],
                'pools_members':
                [{
                    'id':
                    pool_member['id'],
                    'identifier':
                    pool_member['identifier'],
                    'ip':
                    pool_member['ip']['ip_formated'] if pool_member['ip'] else
                    pool_member['ipv6']['ip_formated'],
                    'port':
                    pool_member['port_real'],
                    'member_status':
                    pool_member['member_status'],
                    'limit':
                    pool_member['limit'],
                    'priority':
                    pool_member['priority'],
                    'weight':
                    pool_member['weight']
                }
                 for pool_member in pool_serializer.data['server_pool_members']
                 ]
            }

            vip_request['ports'][idx]['pools'][i]['l7_rule'] = l7_rule
        l7_protocol = OptionVip.objects.get(id=port['options']['l7_protocol'])
        l4_protocol = OptionVip.objects.get(id=port['options']['l4_protocol'])

        vip_request['ports'][idx]['options'] = dict()
        vip_request['ports'][idx]['options']['l7_protocol'] = {
            'id': l7_protocol.id,
            'nome_opcao_txt': l7_protocol.nome_opcao_txt
        }
        vip_request['ports'][idx]['options']['l4_protocol'] = {
            'id': l4_protocol.id,
            'nome_opcao_txt': l4_protocol.nome_opcao_txt
        }

    vip_request['conf'] = conf

    if conf:
        for idx, layer in enumerate(conf['conf']['layers']):
            requiments = layer.get('requiments')
            if requiments:
                # validate for port
                for idx_port, port in enumerate(vip['ports']):
                    for requiment in requiments:
                        condicionals = requiment.get('condicionals')
                        for condicional in condicionals:

                            validated = True

                            validations = condicional.get('validations')
                            for validation in validations:
                                if validation.get('type') == 'optionvip':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        int(vip['options'][validation.get(
                                            'variable')]),
                                        int(validation.get('value')))

                                if validation.get('type') == 'portoptionvip':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        int(port['options'][validation.get(
                                            'variable')]),
                                        int(validation.get('value')))

                                if validation.get(
                                        'type') == 'field' and validation.get(
                                            'variable') == 'cluster_unit':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        cluster_unit, validation.get('value'))
                            if validated:
                                use = condicional.get('use')
                                for item in use:
                                    definitions = item.get('definitions')
                                    eqpts = item.get('eqpts')
                                    if eqpts:

                                        eqpts = Equipamento.objects.filter(
                                            id__in=eqpts,
                                            maintenance=0,
                                            tipo_equipamento__tipo_equipamento=
                                            u'Balanceador').distinct()

                                        if facade_eqpt.all_equipments_are_in_maintenance(
                                                equips):
                                            raise exceptions_eqpt.AllEquipmentsAreInMaintenanceException(
                                            )

                                        if user:
                                            if not facade_eqpt.all_equipments_can_update_config(
                                                    equips, user):
                                                raise exceptions_eqpt.UserDoesNotHavePermInAllEqptException(
                                                    'User does not have permission to update conf in eqpt. \
                                                    Verify the permissions of user group with equipment group. Vip:{}'
                                                    .format(vip_request['id']))

                                        for eqpt in eqpts:
                                            eqpt_id = str(eqpt.id)

                                            if not load_balance.get(eqpt_id):
                                                equipment_access = EquipamentoAcesso.search(
                                                    equipamento=eqpt.id)

                                                plugin = PluginFactory.factory(
                                                    eqpt)

                                                load_balance[eqpt_id] = {
                                                    'plugin': plugin,
                                                    'access': equipment_access,
                                                    'vips': [],
                                                    'layers': {},
                                                }

                                            idx_layer = str(idx)
                                            idx_port_str = str(port['port'])
                                            if not load_balance[eqpt_id][
                                                    'layers'].get(id_vip):
                                                load_balance[eqpt_id][
                                                    'layers'][id_vip] = dict()

                                            if load_balance[eqpt_id]['layers'][
                                                    id_vip].get(idx_layer):
                                                if load_balance[eqpt_id][
                                                        'layers'][id_vip].get(
                                                            idx_layer).get(
                                                                'definitions'
                                                            ).get(
                                                                idx_port_str):
                                                    load_balance[eqpt_id][
                                                        'layers'][id_vip][
                                                            idx_layer][
                                                                'definitions'][
                                                                    idx_port_str] += definitions
                                                else:
                                                    load_balance[eqpt_id][
                                                        'layers'][id_vip][
                                                            idx_layer][
                                                                'definitions'][
                                                                    idx_port_str] = definitions
                                            else:
                                                load_balance[eqpt_id][
                                                    'layers'][id_vip][
                                                        idx_layer] = {
                                                            'vip_request':
                                                            vip_request,
                                                            'definitions': {
                                                                idx_port_str:
                                                                definitions
                                                            }
                                                        }
                                # In first validated==True stops conditionals.
                                # Removing this break will add a wrong
                                # conditional.
                                break

    for e in equips:
        eqpt_id = str(e.id)

        if not load_balance.get(eqpt_id):

            equipment_access = EquipamentoAcesso.search(equipamento=e.id)

            plugin = PluginFactory.factory(e)

            load_balance[eqpt_id] = {
                'plugin': plugin,
                'access': equipment_access,
                'vips': [],
                'layers': {},
            }

        load_balance[eqpt_id]['vips'].append({'vip_request': vip_request})

    return load_balance
Пример #29
0
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to add an IP and associate it to an equipment.

        URL: ipv6/
        '''

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

        try:

            # Business Validations

            # 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')
            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_network_ipv6')
            description = ip_map.get('description')

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

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

            # Description can NOT be greater than 100
            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

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # New IPv6
                ipv6 = Ipv6()
                ipv6.description = description

                # Persist
                ipv6.create(user, equip_id, network_ipv6_id)

                # Generate return map
                ip_map = dict()
                ip_map['id'] = ipv6.id
                ip_map['id_redeipv6'] = ipv6.networkipv6.id
                ip_map['bloco1'] = ipv6.block1
                ip_map['bloco2'] = ipv6.block2
                ip_map['bloco3'] = ipv6.block3
                ip_map['bloco4'] = ipv6.block4
                ip_map['bloco5'] = ipv6.block5
                ip_map['bloco6'] = ipv6.block6
                ip_map['bloco7'] = ipv6.block7
                ip_map['bloco8'] = ipv6.block8
                ip_map['descricao'] = ipv6.description

                return self.response(dumps_networkapi({'ip': ip_map}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IPv6 to an equipment.

        URL: ipv6/assoc/
        '''

        self.log.info('Associate Ipv6 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
            ip_id = ip_map.get('id_ip')
            equip_id = ip_map.get('id_equip')
            network_ipv6_id = ip_map.get('id_net')

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

            # 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_ipv6_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)

            # 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

            # Get net
            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # Get ip
                ip = Ipv6.get_by_pk(ip_id)
                # Get equipment
                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

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

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

                vlan_atual = net.vlan
                vlan_aux = None
                ambiente_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:
                                ambiente_aux = vlan.ambiente
                                vlan_aux = vlan
                                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))

                # Persist
                try:

                    try:
                        ipEquip = Ipv6Equipament()
                        ipEquip.get_by_ip_equipment(ip.id, equip_id)

                        raise IpEquipmentAlreadyAssociation(
                            None,
                            u'Ipv6 %s:%s:%s:%s:%s:%s:%s:%s already has association with Equipament %s.'
                            % (ip.block1, ip.block2, ip.block3, ip.block4,
                               ip.block5, ip.block6, ip.block7, ip.block8,
                               equip_id))
                    except IpEquipmentNotFoundError, e:
                        pass

                    equipment = Equipamento().get_by_pk(equip_id)
                    ip_equipment = Ipv6Equipament()
                    ip_equipment.ip = ip

                    ip_equipment.equipamento = equipment

                    # Filter case 2 - Adding new IpEquip for a equip that
                    # already have ip in other network with the same range ##

                    # Get all Ipv6Equipament related to this equipment
                    ip_equips = Ipv6Equipament.objects.filter(
                        equipamento=equip_id)

                    for ip_test in [ip_equip.ip for ip_equip in ip_equips]:
                        if ip_test.networkipv6.block1 == ip.networkipv6.block1 and \
                                ip_test.networkipv6.block2 == ip.networkipv6.block2 and \
                                ip_test.networkipv6.block3 == ip.networkipv6.block3 and \
                                ip_test.networkipv6.block4 == ip.networkipv6.block4 and \
                                ip_test.networkipv6.block5 == ip.networkipv6.block5 and \
                                ip_test.networkipv6.block6 == ip.networkipv6.block6 and \
                                ip_test.networkipv6.block7 == ip.networkipv6.block7 and \
                                ip_test.networkipv6.block8 == ip.networkipv6.block8 and \
                                ip_test.networkipv6.block == ip.networkipv6.block and \
                                ip_test.networkipv6 != ip.networkipv6:

                            # Filter testing
                            if ip_test.networkipv6.vlan.ambiente.filter is None or ip.networkipv6.vlan.ambiente.filter is None:
                                raise IpRangeAlreadyAssociation(
                                    None,
                                    u'Equipment is already associated with another ip with the same ip range.'
                                )
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(
                                        filter=ip.networkipv6.vlan.ambiente.
                                        filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

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

                                if equipment.tipo_equipamento not in tp_equip_list_one or equipment.tipo_equipamento not in tp_equip_list_two:
                                    raise IpRangeAlreadyAssociation(
                                        None,
                                        u'Equipment is already associated with another ip with the same ip range.'
                                    )

                    ## Filter case 2 - end ##

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

                    # Makes Environment Equipment association
                    try:
                        equipment_environment = EquipamentoAmbiente()
                        equipment_environment.equipamento = equipment
                        equipment_environment.ambiente = net.vlan.ambiente
                        equipment_environment.create(user)

                    except EquipamentoAmbienteDuplicatedError, e:
                        # If already exists, OK !
                        pass

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to check an IPv4 or Ipv6 for vip request.

        URL: ip/checkvipip/
        '''
        self.log.info('Check a Ipv4 or Ipv6 for Vip')

        try:

            # Business Validations

            # 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
            ip = ip_map.get('ip')
            id_evip = ip_map.get('id_evip')

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

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

            # Valid evip id
            if not is_valid_int_greater_zero_param(id_evip):
                raise InvalidValueError(None, 'id_evip', id_evip)

            # Business Rules

            evip = EnvironmentVip.get_by_pk(id_evip)

            ip_list = ip.split(".")

            if len(ip_list) == 1:

                if not is_valid_ipv6(ip):
                    self.log.error(u'Parameter ip is invalid. Value: %s.', ip)
                    raise InvalidValueError(None, 'ip', ip)

                if len(evip.networkipv6_set.all()) <= 0:
                    raise NetworkNotInEvip(
                        'IPv6', 'Não há rede no ambiente vip fornecido')

                ip_list = ip.split(":")
                ip_checked = Ipv6.get_by_octs_and_environment_vip(ip_list[0], ip_list[1], ip_list[
                                                                  2], ip_list[3], ip_list[4], ip_list[5], ip_list[6], ip_list[7], id_evip)

                ip_ok = False

                for ip_equip in ip_checked.ipv6equipament_set.all():

                    if ip_equip.equipamento.tipo_equipamento == TipoEquipamento.get_tipo_balanceador():

                        ip_ok = True
                        break

                if not ip_ok:
                    raise IpNotAvailableError(
                        None, "Ipv6 indisponível para o Ambiente Vip: %s, pois não existe equipamento do Tipo Balanceador relacionado a este Ip." % evip.show_environment_vip())

            else:

                if not is_valid_ipv4(ip):
                    self.log.error(u'Parameter ip is invalid. Value: %s.', ip)
                    raise InvalidValueError(None, 'ip', ip)

                if len(evip.networkipv4_set.all()) <= 0:
                    raise NetworkNotInEvip(
                        'IPv4', 'Não há rede no ambiente vip fornecido')

                ip_checked = Ip.get_by_octs_and_environment_vip(
                    ip_list[0], ip_list[1], ip_list[2], ip_list[3], id_evip)

                ip_ok = False

                for ip_equip in ip_checked.ipequipamento_set.all():

                    if ip_equip.equipamento.tipo_equipamento == TipoEquipamento.get_tipo_balanceador():

                        ip_ok = True
                        break

                if not ip_ok:
                    raise IpNotAvailableError(
                        None, "Ipv4 indisponível para o Ambiente Vip: %s, pois não existe equipamento do Tipo Balanceador relacionado a este Ip." % evip.show_environment_vip())

            ip_dict = model_to_dict(ip_checked)

            return self.response(dumps_networkapi({'ip': ip_dict}))

        except NetworkNotInEvip, e:
            return self.response_error(321, e.cause)
    def handle_post(self, request, user, *args, **kwargs):
        """
        Handles POST requests to list all the VIPs related to IPv6.

        URL: vip/ipv6/all/
        """

        self.log.info('Get all the VIPs related to IPv6')

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Business Validations

            # 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:
                return self.response_error(3, u'There is no value to the networkapi tag of XML request.')

            vip_map = networkapi_map.get('vip')
            if vip_map is None:
                return self.response_error(3, u'There is no value to the vip tag of XML request.')

            # Get XML data
            ip_str = str(vip_map['ipv6'])
            all_prop = str(vip_map['all_prop'])

            # Valid IPv6
            if not is_valid_ipv6(ip_str):
                self.log.error(
                    u'Parameter ipv6 is invalid. Value: %s.', ip_str)
                raise InvalidValueError(None, 'ipv6', ip_str)

            # Valid all_prop
            if not is_valid_int_param(all_prop):
                self.log.error(
                    u'Parameter all_prop is invalid. Value: %s.', all_prop)
                raise InvalidValueError(None, 'all_prop', all_prop)
            all_prop = int(all_prop)
            if all_prop not in (0, 1):
                self.log.error(
                    u'Parameter all_prop is invalid. Value: %s.', all_prop)
                raise InvalidValueError(None, 'all_prop', all_prop)

            blocks = str(IPv6Address(ip_str).exploded).split(':')

            # Find Ipv6 by blocks to check if it exist
            ipv6 = Ipv6.get_by_blocks(blocks[0], blocks[1], blocks[2], blocks[
                                      3], blocks[4], blocks[5], blocks[6], blocks[7])

            # Business Rules
            list_ips = []
            for ip in ipv6:

                ips_map = dict()
                ips_map = model_to_dict(ip)

                # Find all VIPs related to ipv6
                if all_prop == 1:
                    ips_map['vips'] = ip.requisicaovips_set.all().values()
                else:
                    vips = ip.requisicaovips_set.all().values_list(
                        'id', flat=True)
                    ips_map['vips'] = [int(item) for item in vips]

                list_ips.append(ips_map)

            # Return XML
            vips_map = dict()
            vips_map['ips'] = list_ips

            return self.response(dumps_networkapi(vips_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4 and ipv6 of determined Equip.

        URLs: ip/getbyequip/id_equip
        """

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_equip = kwargs.get('id_equip')

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            # Business Rules
            listadeIps6 = []
            listaDeIps4 = []

            equip = Equipamento.get_by_pk(id_equip)

            ipEquip = IpEquipamento()
            ips = ipEquip.list_by_equip(equip.id)

            for ip4 in ips:
                listaDeIps4.append(Ip.get_by_pk(ip4.ip.id))

            ips = Ipv6Equipament.list_by_equip(equip.id)

            for ip6 in ips:
                listadeIps6.append(Ipv6.get_by_pk(ip6.ip.id))

            network_map = dict()

            list_ips = []
            list_ip4 = []
            list_ip6 = []

            dict_ips = dict()
            ip4_maps = dict()
            ip6_maps = dict()

            for ip4 in listaDeIps4:

                ip4_maps['id'] = ip4.id
                ip4_maps['oct1'] = ip4.oct1
                ip4_maps['oct2'] = ip4.oct2
                ip4_maps['oct3'] = ip4.oct3
                ip4_maps['oct4'] = ip4.oct4
                ip4_maps['descricao'] = ip4.descricao
                ip4_maps['id_rede'] = ip4.networkipv4_id
                list_ip4.append(ip4_maps)
                ip4_maps = dict()

            for ip6 in listadeIps6:

                ip6_maps['id'] = ip6.id
                ip6_maps['block1'] = ip6.block1
                ip6_maps['block2'] = ip6.block2
                ip6_maps['block3'] = ip6.block3
                ip6_maps['block4'] = ip6.block4
                ip6_maps['block5'] = ip6.block5
                ip6_maps['block6'] = ip6.block6
                ip6_maps['block7'] = ip6.block7
                ip6_maps['block8'] = ip6.block8
                ip6_maps['descricao'] = ip6.description
                ip6_maps['id_rede'] = ip6.networkipv6_id
                list_ip6.append(ip6_maps)
                ip6_maps = dict()

            dict_ips['ipv4'] = list_ip4
            dict_ips['ipv6'] = list_ip6
            list_ips.append(dict_ips)

            network_map['ips'] = list_ips

            # Return XML
            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IPv6 to an equipment.

        URL: ipv6/assoc/
        '''

        self.log.info('Associate Ipv6 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
            ip_id = ip_map.get('id_ip')
            equip_id = ip_map.get('id_equip')
            network_ipv6_id = ip_map.get('id_net')

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

            # 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_ipv6_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)

            # 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

            # Get net
            net = NetworkIPv6.get_by_pk(network_ipv6_id)

            with distributedlock(LOCK_NETWORK_IPV6 % network_ipv6_id):

                # Get ip
                ip = Ipv6.get_by_pk(ip_id)
                # Get equipment
                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

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

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

                vlan_atual = net.vlan
                vlan_aux = None
                ambiente_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:
                                ambiente_aux = vlan.ambiente
                                vlan_aux = vlan
                                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))

                # Persist
                try:

                    try:
                        ipEquip = Ipv6Equipament()
                        ipEquip.get_by_ip_equipment(ip.id, equip_id)

                        raise IpEquipmentAlreadyAssociation(None, u'Ipv6 %s:%s:%s:%s:%s:%s:%s:%s already has association with Equipament %s.' % (
                            ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8, equip_id))
                    except IpEquipmentNotFoundError, e:
                        pass

                    equipment = Equipamento().get_by_pk(equip_id)
                    ip_equipment = Ipv6Equipament()
                    ip_equipment.ip = ip

                    ip_equipment.equipamento = equipment

                    # Filter case 2 - Adding new IpEquip for a equip that
                    # already have ip in other network with the same range ##

                    # Get all Ipv6Equipament related to this equipment
                    ip_equips = Ipv6Equipament.objects.filter(
                        equipamento=equip_id)

                    for ip_test in [ip_equip.ip for ip_equip in ip_equips]:
                        if ip_test.networkipv6.block1 == ip.networkipv6.block1 and \
                                ip_test.networkipv6.block2 == ip.networkipv6.block2 and \
                                ip_test.networkipv6.block3 == ip.networkipv6.block3 and \
                                ip_test.networkipv6.block4 == ip.networkipv6.block4 and \
                                ip_test.networkipv6.block5 == ip.networkipv6.block5 and \
                                ip_test.networkipv6.block6 == ip.networkipv6.block6 and \
                                ip_test.networkipv6.block7 == ip.networkipv6.block7 and \
                                ip_test.networkipv6.block8 == ip.networkipv6.block8 and \
                                ip_test.networkipv6.block == ip.networkipv6.block and \
                                ip_test.networkipv6 != ip.networkipv6:

                            # Filter testing
                            if ip_test.networkipv6.vlan.ambiente.filter is None or ip.networkipv6.vlan.ambiente.filter is None:
                                raise IpRangeAlreadyAssociation(
                                    None, u'Equipment is already associated with another ip with the same ip range.')
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=ip.networkipv6.vlan.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

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

                                if equipment.tipo_equipamento not in tp_equip_list_one or equipment.tipo_equipamento not in tp_equip_list_two:
                                    raise IpRangeAlreadyAssociation(
                                        None, u'Equipment is already associated with another ip with the same ip range.')

                    ## Filter case 2 - end ##

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

                    # Makes Environment Equipment association
                    try:
                        equipment_environment = EquipamentoAmbiente()
                        equipment_environment.equipamento = equipment
                        equipment_environment.ambiente = net.vlan.ambiente
                        equipment_environment.create(user)

                    except EquipamentoAmbienteDuplicatedError, e:
                        # If already exists, OK !
                        pass

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
    def network_ipv6_add(self, user, vlan_id, network_type, environment_vip, prefix=None):

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

            # Network Type

            # Valid network_type ID
            """
            if not is_valid_int_greater_zero_param(network_type):
                self.log.error(
                    u'Parameter id_tipo_rede is invalid. Value: %s.', network_type)
                raise InvalidValueError(None, 'id_tipo_rede', network_type)
            """
            # Find network_type by ID to check if it exist
            net = None
            if network_type:
                net = TipoRede.get_by_pk(network_type)

            # Environment Vip

            if environment_vip is not None:

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

                # Find Environment VIP by ID to check if it exist
                evip = EnvironmentVip.get_by_pk(environment_vip)

            else:
                evip = None

            # Business Rules

            # New NetworkIPv6
            network_ipv6 = NetworkIPv6()
            vlan_map = network_ipv6.add_network_ipv6(
                user, vlan_id, net, evip, prefix)

            list_equip_routers_ambient = EquipamentoAmbiente.get_routers_by_environment(
                vlan_map['vlan']['id_ambiente'])

            if list_equip_routers_ambient:

                # Add Adds the first available ipv6 on all equipment
                # that is configured as a router for the environment related to
                # network
                ipv6 = Ipv6.get_first_available_ip6(
                    vlan_map['vlan']['id_network'])

                ipv6 = str(ipv6).split(':')

                ipv6_model = Ipv6()
                ipv6_model.block1 = ipv6[0]
                ipv6_model.block2 = ipv6[1]
                ipv6_model.block3 = ipv6[2]
                ipv6_model.block4 = ipv6[3]
                ipv6_model.block5 = ipv6[4]
                ipv6_model.block6 = ipv6[5]
                ipv6_model.block7 = ipv6[6]
                ipv6_model.block8 = ipv6[7]
                ipv6_model.networkipv6_id = vlan_map['vlan']['id_network']

                ipv6_model.save()

                if len(list_equip_routers_ambient) > 1:
                    multiple_ips = True
                else:
                    multiple_ips = False

                for equip in list_equip_routers_ambient:

                    Ipv6Equipament().create(
                        user, ipv6_model.id, equip.equipamento.id)

                    if multiple_ips:
                        router_ip = Ipv6.get_first_available_ip6(
                            vlan_map['vlan']['id_network'], True)
                        router_ip = str(router_ip).split(':')
                        ipv6_model2 = Ipv6()
                        ipv6_model2.block1 = router_ip[0]
                        ipv6_model2.block2 = router_ip[1]
                        ipv6_model2.block3 = router_ip[2]
                        ipv6_model2.block4 = router_ip[3]
                        ipv6_model2.block5 = router_ip[4]
                        ipv6_model2.block6 = router_ip[5]
                        ipv6_model2.block7 = router_ip[6]
                        ipv6_model2.block8 = router_ip[7]
                        ipv6_model2.networkipv6_id = vlan_map[
                            'vlan']['id_network']
                        ipv6_model2.save()
                        Ipv6Equipament().create(user, ipv6_model2.id, equip.equipamento.id)

            # Return XML
            return self.response(dumps_networkapi(vlan_map))

        except XMLError, e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
Пример #36
0
def save_server_pool_member(user, sp, list_server_pool_member):

    list_pool_member = list()
    old_priorities_list = list()
    # Remove empty values from list
    id_pool_member_noempty = [x['id_pool_member'] for x in list_server_pool_member if x['id_pool_member'] != '']

    #exclue server pool member
    del_smp = sp.serverpoolmember_set.exclude(id__in=id_pool_member_noempty)
    if del_smp:
        for obj in del_smp:

            obj.delete(user)

            #execute script remove real if pool already created
            #commit transaction after each successful script call
            if sp.pool_created:
                command = settings.POOL_REAL_REMOVE % (obj.server_pool_id, obj.ip_id if obj.ip else obj.ipv6_id, obj.port_real)
                code, _, _ = exec_script(command)
                if code != 0:
                    raise exceptions.ScriptCreatePoolException()
                transaction.commit()

    if list_server_pool_member:
        apply_new_priorities = False
        for dic in list_server_pool_member:
        #
            ip_object = None
            ipv6_object = None
            if len(dic['ip']) <= 15:
                ip_object = Ip.get_by_pk(dic['id'])
            else:
                ipv6_object = Ipv6.get_by_pk(dic['id'])

            id_pool = sp.id
            id_ip = ip_object and ip_object.id or ipv6_object and ipv6_object.id
            port_ip = dic['port_real']

            if dic['id_pool_member']:
                spm = ServerPoolMember.objects.get(id=dic['id_pool_member'])
                spm.server_pool = sp
                spm.identifier = dic['nome_equips']
                spm.ip = ip_object
                spm.ipv6 = ipv6_object
                spm.weight = dic['weight']
                spm.limit = sp.default_limit
                old_spm_priority = spm.priority
                old_priorities_list.append(old_spm_priority)
                spm.priority = dic['priority']
                spm.port_real = dic['port_real']
                spm.save(user)
                if(old_spm_priority != spm.priority and sp.pool_created):
                    apply_new_priorities = True
            else:
                spm = ServerPoolMember(server_pool=sp, identifier=dic['nome_equips'], ip=ip_object, ipv6=ipv6_object,
                                       priority=dic['priority'], weight=dic['weight'], limit=sp.default_limit,
                                       port_real=dic['port_real'])
                spm.save(user)

                old_priorities_list.append(dic['priority'])

                #execute script to create real if pool already created
                #commits transaction. Rolls back if script returns error
                if sp.pool_created:
                    transaction.commit()
                    #def prepare_and_save(self, server_pool, ip, ip_type, priority, weight, port_real, user, commit=False):
                    #spm.prepare_and_save(sp, ip_object, IP_VERSION.IPv4[1], dic['priority'], dic['weight'], dic['port_real'], user, True)
                    command = settings.POOL_REAL_CREATE % (id_pool, id_ip, port_ip)
                    code, _, _ = exec_script(command)
                    if code != 0:
                        spm.delete(user)
                        transaction.commit()
                        raise exceptions.ScriptCreatePoolException()

                #if sp.healthcheck_id:
                #    spm.healthcheck = sp.healthcheck
            list_pool_member.append(spm)

        #Applies new priority in pool - only 1 script run for all members
        if(apply_new_priorities):
            transaction.commit()
            command = settings.POOL_MEMBER_PRIORITIES % (sp.id)
            code, _, _ = exec_script(command)
            if code != 0:
                for i in len(old_priorities_list):
                    list_pool_member[i].priority = old_priorities_list[i]
                    list_pool_member[i].save(user)
                transaction.commit()
                raise exceptions.ScriptAlterPriorityPoolMembersException()

    return list_pool_member
Пример #37
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv6.

        URLs: ipv6/get/id_ip6
        """

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_ip = kwargs.get('id_ipv6')

            if not is_valid_int_greater_zero_param(id_ip):
                raise InvalidValueError(None, 'id_ip', id_ip)

            # Business Rules

            ip = Ipv6()

            ip = ip.get_by_pk(id_ip)

            EquipIps = []
            mapa = dict()
            # lista = []

            try:

                EquipIps = []
                equipsIp = Ipv6Equipament.list_by_ip6(ip.id)
                for eIp in equipsIp:
                    EquipIps.append(eIp)
                mapa[ip.id] = EquipIps
                # lista.append(mapa)

            except IpEquipmentNotFoundError:
                EquipIps.append(None)
            except IpError:
                EquipIps.append(None)

            network_map = dict()

            list_ips = []
            lequips = []

            lequips = []
            ip_maps = dict()
            ip_maps['id'] = ip.id
            ip_maps['block1'] = ip.block1
            ip_maps['block2'] = ip.block2
            ip_maps['block3'] = ip.block3
            ip_maps['block4'] = ip.block4
            ip_maps['block5'] = ip.block5
            ip_maps['block6'] = ip.block6
            ip_maps['block7'] = ip.block7
            ip_maps['block8'] = ip.block8
            ip_maps['descricao'] = ip.description
            for equip in mapa.get(ip.id):
                equip = Equipamento.get_by_pk(equip.equipamento.id)
                lequips.append(model_to_dict(equip))
            ip_maps['equipamento'] = lequips
            list_ips.append(ip_maps)

            list_ips

            network_map['ips'] = list_ips

            # Return XML
            return self.response(dumps_networkapi(network_map))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
    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)
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to check an IPv4 or Ipv6 for vip request.

        URL: ip/checkvipip/
        """
        self.log.info('Check a Ipv4 or Ipv6 for Vip')

        from networkapi.equipamento.models import TipoEquipamento

        try:

            # Business Validations

            # 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
            ip = ip_map.get('ip')
            id_evip = ip_map.get('id_evip')

            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

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

            # Valid evip id
            if not is_valid_int_greater_zero_param(id_evip):
                raise InvalidValueError(None, 'id_evip', id_evip)

            # Business Rules

            evip = EnvironmentVip.get_by_pk(id_evip)

            ip_list = ip.split('.')

            if len(ip_list) == 1:

                if not is_valid_ipv6(ip):
                    self.log.error(u'Parameter ip is invalid. Value: %s.', ip)
                    raise InvalidValueError(None, 'ip', ip)

                if len(evip.networkipv6_set.all()) <= 0:
                    raise NetworkNotInEvip(
                        'IPv6', 'Não há rede no ambiente vip fornecido')

                ip_list = ip.split(':')
                ip_checked = Ipv6.get_by_octs_and_environment_vip(
                    ip_list[0], ip_list[1], ip_list[2], ip_list[3], ip_list[4],
                    ip_list[5], ip_list[6], ip_list[7], id_evip)

                ip_ok = False

                for ip_equip in ip_checked.ipv6equipament_set.all():

                    if ip_equip.equipamento.tipo_equipamento == TipoEquipamento.get_tipo_balanceador(
                    ):

                        ip_ok = True
                        break

                if not ip_ok:
                    raise IpNotAvailableError(
                        None,
                        'Ipv6 indisponível para o Ambiente Vip: %s, pois não existe equipamento do Tipo Balanceador relacionado a este Ip.'
                        % evip.show_environment_vip())

            else:

                if not is_valid_ipv4(ip):
                    self.log.error(u'Parameter ip is invalid. Value: %s.', ip)
                    raise InvalidValueError(None, 'ip', ip)

                if len(evip.networkipv4_set.all()) <= 0:
                    raise NetworkNotInEvip(
                        'IPv4', 'Não há rede no ambiente vip fornecido')

                ip_checked = Ip.get_by_octs_and_environment_vip(
                    ip_list[0], ip_list[1], ip_list[2], ip_list[3], id_evip)

                ip_ok = False

                for ip_equip in ip_checked.ipequipamento_set.all():

                    if ip_equip.equipamento.tipo_equipamento == TipoEquipamento.get_tipo_balanceador(
                    ):

                        ip_ok = True
                        break

                if not ip_ok:
                    raise IpNotAvailableError(
                        None,
                        'Ipv4 indisponível para o Ambiente Vip: %s, pois não existe equipamento do Tipo Balanceador relacionado a este Ip.'
                        % evip.show_environment_vip())

            ip_dict = model_to_dict(ip_checked)

            return self.response(dumps_networkapi({'ip': ip_dict}))

        except NetworkNotInEvip, e:
            return self.response_error(321, e.cause)
Пример #40
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)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to edit an IP6.

        URL: ipv6/edit/
        '''

        self.log.info('Edit 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
            id_ip = ip_map.get('id_ip')
            description = ip_map.get('descricao')
            ip6 = ip_map.get('ip6')

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

            # Description can NOT be greater than 100
            if not is_valid_string_maxsize(ip6, 39):
                self.log.error(u'Parameter descricao 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):
                raise UserNotAuthorizedError(
                    None,
                    u'User does not have permission to perform the operation.')

            # Business Rules

            # New IP

            ipv6 = Ipv6()

            ipv6 = ipv6.get_by_pk(id_ip)

            with distributedlock(LOCK_IPV6 % id_ip):

                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
                ipv6.edit_ipv6(user)

                return self.response(dumps_networkapi({}))

        except IpNotFoundError, e:
            return self.response_error(150, e.message)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to verify that the IPv6 belongs to environment.

        URL:  /ipv6/environment/
        """

        self.log.info('Verify that the IPv6 belongs to environment')

        try:

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # 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:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            ipv6_map = networkapi_map.get('ipv6_map')
            if ipv6_map is None:
                return self.response_error(3, u'There is no value to the ipv6_map tag  of XML request.')

            # Get XML data
            environment_id = ipv6_map.get('id_environment')
            ipv6 = ipv6_map.get('ipv6')

            # Valid Environment ID
            if not is_valid_int_greater_zero_param(environment_id):
                self.log.error(
                    u'The id_environment parameter is not a valid value: %s.', environment_id)
                raise InvalidValueError(None, 'id_environment', environment_id)

            # Valid IPv6 ID
            if not is_valid_ipv6(ipv6):
                self.log.error(
                    u'The ipv6 parameter is not a valid value: %s.', ipv6)
                raise InvalidValueError(None, 'ipv6', ipv6)

            blocks = str(IPv6Address(ipv6).exploded).split(':')

            # Find Environment by ID to check if it exist
            environment = Ambiente.get_by_pk(environment_id)

            # Find Ipv6 by blocks to check if it exist
            IPv6 = Ipv6.get_by_octs_and_environment(blocks[0], blocks[1], blocks[2], blocks[
                                                    3], blocks[4], blocks[5], blocks[6], blocks[7], environment_id)

            # Generate return map
            ipv6_map = dict()
            ipv6_map['id'] = IPv6.id
            ipv6_map['id_vlan'] = IPv6.networkipv6.vlan.id
            ipv6_map['bloco1'] = IPv6.block1
            ipv6_map['bloco2'] = IPv6.block2
            ipv6_map['bloco3'] = IPv6.block3
            ipv6_map['bloco4'] = IPv6.block4
            ipv6_map['bloco5'] = IPv6.block5
            ipv6_map['bloco6'] = IPv6.block6
            ipv6_map['bloco7'] = IPv6.block7
            ipv6_map['bloco8'] = IPv6.block8
            ipv6_map['descricao'] = IPv6.description

            return self.response(dumps_networkapi({'ipv6': ipv6_map}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Пример #43
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to insert vlan

        URL: vlan/insert/
        """

        try:
            # Generic method for v4 and v6
            network_version = kwargs.get('network_version')

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # 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)
            vlan_map = networkapi_map.get('vlan')
            if vlan_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            environment_id = vlan_map.get('environment_id')
            number = vlan_map.get('number')
            name = vlan_map.get('name')
            acl_file = vlan_map.get('acl_file')
            acl_file_v6 = vlan_map.get('acl_file_v6')
            description = vlan_map.get('description')
            network_ipv4 = vlan_map.get('network_ipv4')
            network_ipv6 = vlan_map.get('network_ipv6')
            vrf = vlan_map.get('vrf')

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

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

            # Valid name of Vlan
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 50):
                self.log.error(u'Parameter name is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name', name)

            if not network_ipv4 or not str(network_ipv4).isdigit():
                self.log.error(
                    u'Parameter network_ipv4 is invalid. Value: %s.', network_ipv4)
                raise InvalidValueError(None, 'network_ipv4', network_ipv4)

            if not network_ipv6 or not str(network_ipv6).isdigit():
                self.log.error(
                    u'Parameter network_ipv6 is invalid. Value: %s.', network_ipv6)
                raise InvalidValueError(None, 'network_ipv6', network_ipv6)

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

            network_ipv4 = int(network_ipv4)
            network_ipv6 = int(network_ipv6)

            if network_ipv4 not in range(0, 2):
                self.log.error(
                    u'Parameter network_ipv4 is invalid. Value: %s.', network_ipv4)
                raise InvalidValueError(None, 'network_ipv4', network_ipv4)

            if network_ipv6 not in range(0, 2):
                self.log.error(
                    u'Parameter network_ipv6 is invalid. Value: %s.', network_ipv6)
                raise InvalidValueError(None, 'network_ipv6', network_ipv6)

            p = re.compile('^[A-Z0-9-_]+$')
            m = p.match(name)

            if not m:
                name = name.upper()
                m = p.match(name)

                if not m:
                    raise InvalidValueError(None, 'name', name)

            # Valid description of Vlan
            if not is_valid_string_minsize(description, 3, False) or not is_valid_string_maxsize(description, 200, False):
                self.log.error(
                    u'Parameter description is invalid. Value: %s', description)
                raise InvalidValueError(None, 'description', description)

            vlan = Vlan()

            # Valid acl_file Vlan
            if acl_file is not None:
                if not is_valid_string_minsize(acl_file, 3) or not is_valid_string_maxsize(acl_file, 200):
                    self.log.error(
                        u'Parameter acl_file is invalid. Value: %s', acl_file)
                    raise InvalidValueError(None, 'acl_file', acl_file)
                p = re.compile('^[A-Z0-9-_]+$')
                m = p.match(acl_file)
                if not m:
                    raise InvalidValueError(None, 'acl_file', acl_file)

                # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                # commenting acl name check - issue #55
                # vlan.get_vlan_by_acl(acl_file)

            # Valid acl_file_v6 Vlan
            if acl_file_v6 is not None:
                if not is_valid_string_minsize(acl_file_v6, 3) or not is_valid_string_maxsize(acl_file_v6, 200):
                    self.log.error(
                        u'Parameter acl_file_v6 is invalid. Value: %s', acl_file_v6)
                    raise InvalidValueError(None, 'acl_file_v6', acl_file_v6)
                p = re.compile('^[A-Z0-9-_]+$')
                m = p.match(acl_file_v6)
                if not m:
                    raise InvalidValueError(None, 'acl_file_v6', acl_file_v6)

                # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                # commenting acl name check - issue #55
                # vlan.get_vlan_by_acl_v6(acl_file_v6)

            ambiente = Ambiente()
            ambiente = ambiente.get_by_pk(environment_id)

            vlan.acl_file_name = acl_file
            vlan.acl_file_name_v6 = acl_file_v6
            vlan.num_vlan = number
            vlan.nome = name
            vlan.descricao = description
            vlan.ambiente = ambiente
            vlan.ativada = 0
            vlan.acl_valida = 0
            vlan.acl_valida_v6 = 0

            vlan.insert_vlan(user)

            if network_ipv4:
                network_ipv4 = NetworkIPv4()
                vlan_map = network_ipv4.add_network_ipv4(
                    user, vlan.id, None, None, None)
                list_equip_routers_ambient = EquipamentoAmbiente.objects.select_related('equipamento').filter(
                    ambiente=vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:

                    # Add Adds the first available ipv4 on all equipment
                    # that is configured as a router for the environment related to
                    # network
                    ip = Ip.get_first_available_ip(network_ipv4.id)

                    ip = str(ip).split('.')

                    ip_model = Ip()
                    ip_model.oct1 = ip[0]
                    ip_model.oct2 = ip[1]
                    ip_model.oct3 = ip[2]
                    ip_model.oct4 = ip[3]
                    ip_model.networkipv4_id = network_ipv4.id

                    ip_model.save(user)

                    if len(list_equip_routers_ambient) > 1 and network_ipv4.block < 30:
                        multiple_ips = True
                    else:
                        multiple_ips = False

                    for equip in list_equip_routers_ambient:
                        IpEquipamento().create(user, ip_model.id, equip.equipamento.id)

                        if multiple_ips:
                            router_ip = Ip.get_first_available_ip(
                                network_ipv4.id, True)
                            router_ip = str(router_ip).split('.')
                            ip_model2 = Ip()
                            ip_model2.oct1 = router_ip[0]
                            ip_model2.oct2 = router_ip[1]
                            ip_model2.oct3 = router_ip[2]
                            ip_model2.oct4 = router_ip[3]
                            ip_model2.networkipv4_id = network_ipv4.id
                            ip_model2.save(user)
                            IpEquipamento().create(user, ip_model2.id, equip.equipamento.id)

            if network_ipv6:
                network_ipv6 = NetworkIPv6()
                vlan_map = network_ipv6.add_network_ipv6(
                    user, vlan.id, None, None, None)

                list_equip_routers_ambient = EquipamentoAmbiente.objects.filter(
                    ambiente=vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:

                    # Add Adds the first available ipv6 on all equipment
                    # that is configured as a router for the environment related to
                    # network
                    ipv6 = Ipv6.get_first_available_ip6(network_ipv6.id)

                    ipv6 = str(ipv6).split(':')

                    ipv6_model = Ipv6()
                    ipv6_model.block1 = ipv6[0]
                    ipv6_model.block2 = ipv6[1]
                    ipv6_model.block3 = ipv6[2]
                    ipv6_model.block4 = ipv6[3]
                    ipv6_model.block5 = ipv6[4]
                    ipv6_model.block6 = ipv6[5]
                    ipv6_model.block7 = ipv6[6]
                    ipv6_model.block8 = ipv6[7]
                    ipv6_model.networkipv6_id = network_ipv6.id

                    ipv6_model.save(user)

                    if len(list_equip_routers_ambient) > 1:
                        multiple_ips = True
                    else:
                        multiple_ips = False

                    for equip in list_equip_routers_ambient:

                        Ipv6Equipament().create(
                            user, ipv6_model.id, equip.equipamento.id)

                        if multiple_ips:
                            router_ip = Ipv6.get_first_available_ip6(
                                network_ipv6.id, True)
                            router_ip = str(router_ip).split(':')
                            ipv6_model2 = Ipv6()
                            ipv6_model2.block1 = router_ip[0]
                            ipv6_model2.block2 = router_ip[1]
                            ipv6_model2.block3 = router_ip[2]
                            ipv6_model2.block4 = router_ip[3]
                            ipv6_model2.block5 = router_ip[4]
                            ipv6_model2.block6 = router_ip[5]
                            ipv6_model2.block7 = router_ip[6]
                            ipv6_model2.block8 = router_ip[7]
                            ipv6_model2.networkipv6_id = network_ipv6.id
                            ipv6_model2.save(user)
                            Ipv6Equipament().create(user, ipv6_model2.id, equip.equipamento.id)

            map = dict()
            listaVlan = dict()
            listaVlan['id'] = vlan.id
            listaVlan['nome'] = vlan.nome
            listaVlan['acl_file_name'] = vlan.acl_file_name
            listaVlan['descricao'] = vlan.descricao
            listaVlan['id_ambiente'] = vlan.ambiente.id
            listaVlan['ativada'] = vlan.ativada
            listaVlan['acl_valida'] = vlan.acl_valida
            map['vlan'] = listaVlan

            # Delete vlan's cache
            # destroy_cache_function()

            # Return XML
            return self.response(dumps_networkapi(map))

        except VlanACLDuplicatedError, e:
            return self.response_error(311, acl_file)
Пример #44
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to verify that the IPv6 belongs to environment.

        URL:  /ipv6/environment/
        """

        self.log.info('Verify that the IPv6 belongs to environment')

        try:

            # User permission
            if not has_perm(user, AdminPermission.IPS,
                            AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # 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:
                return self.response_error(
                    3,
                    u'There is no value to the networkapi tag  of XML request.'
                )

            ipv6_map = networkapi_map.get('ipv6_map')
            if ipv6_map is None:
                return self.response_error(
                    3,
                    u'There is no value to the ipv6_map tag  of XML request.')

            # Get XML data
            environment_id = ipv6_map.get('id_environment')
            ipv6 = ipv6_map.get('ipv6')

            # Valid Environment ID
            if not is_valid_int_greater_zero_param(environment_id):
                self.log.error(
                    u'The id_environment parameter is not a valid value: %s.',
                    environment_id)
                raise InvalidValueError(None, 'id_environment', environment_id)

            # Valid IPv6 ID
            if not is_valid_ipv6(ipv6):
                self.log.error(u'The ipv6 parameter is not a valid value: %s.',
                               ipv6)
                raise InvalidValueError(None, 'ipv6', ipv6)

            blocks = str(IPv6Address(ipv6).exploded).split(':')

            # Find Environment by ID to check if it exist
            environment = Ambiente.get_by_pk(environment_id)

            # Find Ipv6 by blocks to check if it exist
            IPv6 = Ipv6.get_by_octs_and_environment(blocks[0], blocks[1],
                                                    blocks[2], blocks[3],
                                                    blocks[4], blocks[5],
                                                    blocks[6], blocks[7],
                                                    environment_id)

            # Generate return map
            ipv6_map = dict()
            ipv6_map['id'] = IPv6.id
            ipv6_map['id_vlan'] = IPv6.networkipv6.vlan.id
            ipv6_map['bloco1'] = IPv6.block1
            ipv6_map['bloco2'] = IPv6.block2
            ipv6_map['bloco3'] = IPv6.block3
            ipv6_map['bloco4'] = IPv6.block4
            ipv6_map['bloco5'] = IPv6.block5
            ipv6_map['bloco6'] = IPv6.block6
            ipv6_map['bloco7'] = IPv6.block7
            ipv6_map['bloco8'] = IPv6.block8
            ipv6_map['descricao'] = IPv6.description

            return self.response(dumps_networkapi({'ipv6': ipv6_map}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Network

        URL: network/add/
        """

        try:

            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            xml_map, attrs_map = loads(request.raw_post_data)

            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)

            network_map = networkapi_map.get('network')
            if network_map is None:
                msg = u'There is no value to the vlan tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            network = network_map.get('network')
            id_vlan = network_map.get('id_vlan')
            network_type = network_map.get('id_network_type')
            environment_vip = network_map.get('id_environment_vip')
            cluster_unit = network_map.get('cluster_unit')

            try:
                net = IPNetwork(network)
            except ValueError:
                raise InvalidValueError(None, 'network', network)

            # Valid vlan ID
            if not is_valid_int_greater_zero_param(id_vlan):
                raise InvalidValueError(None, 'id_vlan', id_vlan)
            if not is_valid_int_greater_zero_param(network_type):
                raise InvalidValueError(None, 'id_network_type', network_type)

            vlan = Vlan().get_by_pk(id_vlan)
            net_type = TipoRede.get_by_pk(network_type)

            if environment_vip is not None:

                if not is_valid_int_greater_zero_param(environment_vip):
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

                evips = EnvironmentVip.objects.all()
                evip_list = EnvironmentVip.available_evips(
                    EnvironmentVip(), evips, int(id_vlan))

                # Check if the chose environment is in the same environment
                if any(
                        int(environment_vip) == item['id']
                        for item in evip_list):
                    # Find Environment VIP by ID to check if it exist
                    env_vip = EnvironmentVip.get_by_pk(environment_vip)
                else:
                    raise InvalidValueError(None, 'id_environment_vip',
                                            environment_vip)

            else:
                env_vip = None

            # Check unchecked exception
            blocks, network, version = break_network(network)

            expl = split(net.network.exploded,
                         '.' if version == IP_VERSION.IPv4[0] else ':')
            expl.append(str(net.prefixlen))

            if blocks != expl:
                raise InvalidValueError(None, 'rede', network)

            if version == IP_VERSION.IPv4[0]:

                # Find all networks related to environment
                nets = NetworkIPv4.objects.filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([
                    IPv4Network('%d.%d.%d.%d/%d' %
                                (net_ip.oct1, net_ip.oct2, net_ip.oct3,
                                 net_ip.oct4, net_ip.block)) for net_ip in nets
                ])

                # If network selected not in use
                for network_aux in networks:
                    if net in network_aux or network_aux in net:
                        self.log.debug(
                            'Network %s cannot be allocated. It conflicts with %s already '
                            'in use in this environment.' % (net, network))
                        raise NetworkIPv4AddressNotAvailableError(
                            None,
                            u'Network cannot be allocated. %s already in use in this environment.'
                            % network_aux)

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv4.objects.filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([
                        IPv4Network('%d.%d.%d.%d/%d' %
                                    (net_ip.oct1, net_ip.oct2, net_ip.oct3,
                                     net_ip.oct4, net_ip.block))
                        for net_ip in nets
                    ])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    for network_aux in networks:
                        if net in network_aux or network_aux in net:
                            self.log.debug(
                                'Network %s cannot be allocated. It conflicts with %s already in use '
                                'in this environment VIP.' % (net, network))
                            raise NetworkIPv4AddressNotAvailableError(
                                None,
                                u'Network cannot be allocated. %s already in use '
                                u'in this environment VIP.' % network_aux)

                # Check if the new network is in the range of the Environment Network
                try:
                    vlan = Vlan().get_by_pk(id_vlan)
                    vlan_env_id = vlan.ambiente

                    try:
                        config_env = ConfigEnvironment()
                        environment_conf = config_env.get_by_environment(
                            vlan_env_id)

                        if environment_conf:
                            for env_config in environment_conf:

                                ipconfig = env_config.ip_config
                                subnet = ipconfig.subnet

                            env_net = IPNetwork(subnet)

                            try:
                                if net in env_net:
                                    self.log.debug(
                                        'Network "%s" can be allocated because is in the '
                                        'environment network(%s) subnets.' %
                                        (net, subnet))

                                else:
                                    raise NetworkSubnetRange(
                                        None,
                                        'A rede a ser cadastrada (%s) não pertence às '
                                        'subredes do ambiente (rede ambiente: %s). '
                                        'Cadastre o range desejado no '
                                        'ambiente.' % (net, subnet))

                            except NetworkSubnetRange:
                                self.log.error(
                                    'Network "%s" can not be allocated because is not in the '
                                    'environment network(%s) subnets.' %
                                    (net, subnet))
                                return self.response_error(414)

                        else:
                            raise NetworkEnvironmentError(
                                None, 'O ambiente não está configurado. '
                                'É necessário efetuar a configuração.')

                    except NetworkEnvironmentError:
                        self.log.error(
                            'The environment does not have a registered network'
                        )
                        return self.response_error(415)

                except Exception as ERROR:
                    self.log.error(ERROR)

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv4.objects.filter(oct1=expl[0],
                                                  oct2=expl[1],
                                                  oct3=expl[2],
                                                  oct4=expl[3],
                                                  block=expl[4])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[
                                        0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None,
                                        u'Um dos equipamentos associados com o ambiente '
                                        u'desta rede também está associado com outro ambiente '
                                        u'que tem uma rede com essa mesma faixa, adicione '
                                        u'filtros nos ambientes se necessário.'
                                    )
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=other_env_equips[0].
                                            ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or \
                                            env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None,
                                            u'Um dos equipamentos associados com o '
                                            u'ambiente desta rede também está associado '
                                            u'com outro ambiente que tem uma rede com '
                                            u'essa mesma faixa, adicione filtros nos '
                                            u'ambientes se necessário.')

                # # Filter case 1 - end ##

                # New NetworkIPv4
                network_ip = NetworkIPv4()

                network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str(
                    net.network).split('.')
                network_ip.block = net.prefixlen
                network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = \
                    str(net.netmask).split('.')
                network_ip.broadcast = net.broadcast.compressed

            else:
                # Find all networks ralated to environment
                nets = NetworkIPv6.objects.filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                networks = set([
                    IPv6Network('%s:%s:%s:%s:%s:%s:%s:%s/%d' %
                                (net_ip.block1, net_ip.block2, net_ip.block3,
                                 net_ip.block4, net_ip.block5, net_ip.block6,
                                 net_ip.block7, net_ip.block8, net_ip.block))
                    for net_ip in nets
                ])

                # If network selected not in use
                for network_aux in networks:
                    if net in network_aux or network_aux in net:
                        self.log.debug(
                            'Network %s cannot be allocated. It conflicts with %s already in use '
                            'in this environment.' % (net, network))
                        raise NetworkIPv4AddressNotAvailableError(
                            None,
                            u'Network cannot be allocated. %s already in '
                            u'use in this environment.' % network_aux)

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv6.objects.filter(
                        ambient_vip__id=env_vip.id)

                    networks = set([
                        IPv6Network(
                            '%s:%s:%s:%s:%s:%s:%s:%s/%d' %
                            (net_ip.block1, net_ip.block2, net_ip.block3,
                             net_ip.block4, net_ip.block5, net_ip.block6,
                             net_ip.block7, net_ip.block8, net_ip.block))
                        for net_ip in nets
                    ])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    for network_aux in networks:
                        if net in network_aux or network_aux in net:
                            self.log.debug(
                                'Network %s cannot be allocated. It conflicts with %s already in '
                                'use in this environment VIP.' %
                                (net, network))
                            raise NetworkIPv4AddressNotAvailableError(
                                None, u'Network cannot be allocated. %s '
                                u'already in use in this environment '
                                u'VIP.' % network_aux)

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv6.objects.filter(block1=expl[0],
                                                  block2=expl[1],
                                                  block3=expl[2],
                                                  block4=expl[3],
                                                  block5=expl[4],
                                                  block6=expl[5],
                                                  block7=expl[6],
                                                  block8=expl[7],
                                                  block=expl[8])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
                                if other_env_equips[
                                        0].ambiente.filter is None or vlan.ambiente.filter is None:
                                    raise NetworkIPRangeEnvError(
                                        None,
                                        u'Um dos equipamentos associados com o '
                                        u'ambiente desta rede também está associado '
                                        u'com outro ambiente que tem uma rede com '
                                        u'essa mesma faixa, adicione filtros nos '
                                        u'ambientes se necessário.')
                                else:
                                    # Test both environment's filters
                                    tp_equip_list_one = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=vlan.ambiente.filter.id):
                                        tp_equip_list_one.append(fet.equiptype)

                                    tp_equip_list_two = list()
                                    for fet in FilterEquipType.objects.filter(
                                            filter=other_env_equips[0].
                                            ambiente.filter.id):
                                        tp_equip_list_two.append(fet.equiptype)

                                    if env_equip.equipamento.tipo_equipamento not in tp_equip_list_one or \
                                            env_equip.equipamento.tipo_equipamento not in tp_equip_list_two:
                                        raise NetworkIPRangeEnvError(
                                            None,
                                            u'Um dos equipamentos associados com o '
                                            u'ambiente desta rede também está '
                                            u'associado com outro ambiente que tem '
                                            u'uma rede com essa mesma faixa, adicione '
                                            u'filtros nos ambientes se necessário.'
                                        )

                # # Filter case 1 - end ##

                # New NetworkIPv6
                network_ip = NetworkIPv6()
                network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, \
                    network_ip.block6, network_ip.block7, network_ip.block8 = str(net.network.exploded).split(':')
                network_ip.block = net.prefixlen
                network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, \
                    network_ip.mask6, network_ip.mask7, network_ip.mask8 = str(net.netmask.exploded).split(':')

            # Get all vlans environments from equipments of the current
            # environment
            ambiente = vlan.ambiente

            equips = list()
            envs = list()

            # equips = all equipments from the environment which this network
            # is about to be allocated on
            for env in ambiente.equipamentoambiente_set.all():
                equips.append(env.equipamento)

            # envs = all environments from all equips above
            # This will be used to test all networks from the environments.
            for equip in equips:
                for env in equip.equipamentoambiente_set.all():
                    if env.ambiente not in envs:
                        envs.append(env.ambiente)

            network_ip_verify = IPNetwork(network)

            # For all vlans in all common environments,
            # check if any network is a subnetwork or supernetwork
            # of the desired network network_ip_verify
            for env in envs:
                for vlan_obj in env.vlan_set.all():

                    is_subnet = verify_subnet(vlan_obj, network_ip_verify,
                                              version)

                    if is_subnet:
                        if vlan_obj.ambiente == ambiente:
                            raise NetworkIPRangeEnvError(None)

                        if ambiente.filter_id is None or vlan_obj.ambiente.filter_id is None or \
                                int(vlan_obj.ambiente.filter_id) != int(ambiente.filter_id):
                            raise NetworkIPRangeEnvError(None)

            network_ip.vlan = vlan
            network_ip.network_type = net_type
            network_ip.ambient_vip = env_vip
            network_ip.cluster_unit = cluster_unit

            try:

                destroy_cache_function([id_vlan])
                network_ip.save()

                list_equip_routers_ambient = EquipamentoAmbiente.objects.filter(
                    ambiente=network_ip.vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:
                    if version == IP_VERSION.IPv4[0]:
                        if network_ip.block < 31:

                            # Add the first available ipv4 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ip = Ip.get_first_available_ip(network_ip.id)

                            ip = str(ip).split('.')

                            ip_model = Ip()
                            ip_model.oct1 = ip[0]
                            ip_model.oct2 = ip[1]
                            ip_model.oct3 = ip[2]
                            ip_model.oct4 = ip[3]
                            ip_model.networkipv4_id = network_ip.id

                            ip_model.save()

                            if len(list_equip_routers_ambient
                                   ) > 1 and network_ip.block < 30:
                                multiple_ips = True
                            else:
                                multiple_ips = False

                            logging.debug('vxlan: %s' % vlan.vxlan)

                            if vlan.vxlan:

                                logging.debug('vxlan ok')
                                for equip in list_equip_routers_ambient:
                                    IpEquipamento().create(
                                        user, ip_model.id,
                                        equip.equipamento.id)

                                if multiple_ips:
                                    debug_ip = Ip.get_first_available_ip(
                                        network_ip.id, True)

                                    ips = Ip()
                                    ips.oct1, ips.oct2, ips.oct3, ips.oct4 = str(
                                        debug_ip).split('.')
                                    ips.networkipv4_id = network_ip.id
                                    ips.descricao = "IP alocado para debug"
                                    ips.save(user)

                                    IpEquipamento().create(
                                        user, ips.id,
                                        list_equip_routers_ambient[0].
                                        equipamento.id)

                            else:

                                for equip in list_equip_routers_ambient:
                                    IpEquipamento().create(
                                        user, ip_model.id,
                                        equip.equipamento.id)

                                    if multiple_ips:
                                        router_ip = Ip.get_first_available_ip(
                                            network_ip.id, True)
                                        router_ip = str(router_ip).split('.')
                                        ip_model2 = Ip()
                                        ip_model2.oct1 = router_ip[0]
                                        ip_model2.oct2 = router_ip[1]
                                        ip_model2.oct3 = router_ip[2]
                                        ip_model2.oct4 = router_ip[3]
                                        ip_model2.networkipv4_id = network_ip.id
                                        ip_model2.save(user)
                                        IpEquipamento().create(
                                            user, ip_model2.id,
                                            equip.equipamento.id)

                    else:
                        if network_ip.block < 127:

                            # Add the first available ipv6 on all equipment
                            # that is configured as a router for the environment
                            # related to network
                            ipv6 = Ipv6.get_first_available_ip6(network_ip.id)

                            ipv6 = str(ipv6).split(':')

                            ipv6_model = Ipv6()
                            ipv6_model.block1 = ipv6[0]
                            ipv6_model.block2 = ipv6[1]
                            ipv6_model.block3 = ipv6[2]
                            ipv6_model.block4 = ipv6[3]
                            ipv6_model.block5 = ipv6[4]
                            ipv6_model.block6 = ipv6[5]
                            ipv6_model.block7 = ipv6[6]
                            ipv6_model.block8 = ipv6[7]
                            ipv6_model.networkipv6_id = network_ip.id

                            ipv6_model.save()

                            if len(list_equip_routers_ambient
                                   ) > 1 and network_ip.block < 126:
                                multiple_ips = True
                            else:
                                multiple_ips = False

                            if vlan.vxlan:

                                for equip in list_equip_routers_ambient:
                                    Ipv6Equipament().create(
                                        user, ipv6_model.id,
                                        equip.equipamento.id)

                                if multiple_ips:
                                    router_ip = Ipv6.get_first_available_ip6(
                                        network_ip.id, True)

                                    ipv6s = Ipv6()
                                    ipv6s.block1, ipv6s.block2, ipv6s.block3, ipv6s.block4, ipv6s.block5, \
                                        ipv6s.block6, ipv6s.block7, ipv6s.block8 = str(router_ip).split(':')
                                    ipv6s.networkipv6_id = network_ip.id
                                    ipv6s.descricao = "IPv6 alocado para debug"
                                    ipv6s.save(user)

                                    Ipv6Equipament().create(
                                        user, ipv6s.id,
                                        list_equip_routers_ambient[0].
                                        equipamento.id)

                            else:

                                for equip in list_equip_routers_ambient:
                                    Ipv6Equipament().create(
                                        user, ipv6_model.id,
                                        equip.equipamento.id)

                                    if multiple_ips:
                                        router_ip = Ipv6.get_first_available_ip6(
                                            network_ip.id, True)
                                        router_ip = str(router_ip).split(':')
                                        ipv6_model2 = Ipv6()
                                        ipv6_model2.block1 = router_ip[0]
                                        ipv6_model2.block2 = router_ip[1]
                                        ipv6_model2.block3 = router_ip[2]
                                        ipv6_model2.block4 = router_ip[3]
                                        ipv6_model2.block5 = router_ip[4]
                                        ipv6_model2.block6 = router_ip[5]
                                        ipv6_model2.block7 = router_ip[6]
                                        ipv6_model2.block8 = router_ip[7]
                                        ipv6_model2.networkipv6_id = network_ip.id
                                        ipv6_model2.save(user)
                                        Ipv6Equipament().create(
                                            user, ipv6_model2.id,
                                            equip.equipamento.id)

            except Exception as e:
                raise IpError(e, u'Error persisting Network.')

            network_map = dict()
            network_map['id'] = network_ip.id
            network_map['rede'] = str(net)
            network_map[
                'broadcast'] = net.broadcast if net.version == 4 else ''
            network_map['mask'] = net.netmask.exploded
            network_map['id_vlan'] = vlan.id
            network_map['id_tipo_rede'] = net_type.id
            network_map[
                'id_ambiente_vip'] = env_vip.id if env_vip is not None else ''
            network_map['active'] = network_ip

            return self.response(dumps_networkapi({'network': network_map}))

        except NetworkIPRangeEnvError:
            return self.response_error(346)
        except InvalidValueError as e:
            self.log.error(u'Parameter %s is invalid. Value: %s.' %
                           (e.param, e.value))
            return self.response_error(269, e.param, e.value)
        except NetworkTypeNotFoundError:
            self.log.error(u'The network_type parameter does not exist.')
            return self.response_error(111)
        except VlanNotFoundError:
            self.log.error(u'Vlan not found')
            return self.response_error(116)
        except EnvironmentVipNotFoundError:
            return self.response_error(283)
        except NetworkIPv4AddressNotAvailableError:
            return self.response_error(295)
        except NetworkIPv6AddressNotAvailableError:
            return self.response_error(296)
        except ConfigEnvironmentInvalidError:
            return self.response_error(294)
        except NetworkIpAddressNotAvailableError:
            return self.response_error(335)
        except (IpError, NetworkIPv6Error, NetworkIPv4Error, GrupoError,
                VlanError):
            return self.response_error(1)
        except XMLError as e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv6 by network ipv6 id.

        URLs: ip/id_network_ipv6/id_rede 
         """

        try:
            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Business Validations

            # Valid id access
            id_network = kwargs.get('id_rede')

            if not is_valid_int_greater_zero_param(id_network):
                raise InvalidValueError(None, 'id_rede', id_network)

            # Business Rules

            NetworkIPv6.get_by_pk(id_network)

            ips = Ipv6.list_by_network(id_network)

            try:
                len(ips)
            except Exception, e:
                raise InvalidValueError(None, 'id_rede', id_network)

            if ips == None or len(ips) <= 0:
                raise IpNotFoundError(305, id_network)

            EquipIps = []
            mapa = dict()
            #lista = []

            try:
                for ip in ips:
                    EquipIps = []
                    equipsIp = Ipv6Equipament.list_by_ip6(ip.id)
                    for eIp in equipsIp:
                        EquipIps.append(eIp)
                    mapa[ip.id] = EquipIps
                    # lista.append(mapa)bora pegar cafe

            except IpEquipmentNotFoundError:
                EquipIps.append(None)
            except IpError:
                EquipIps.append(None)

            network_map = dict()
            list_ips = []
            lequips = []

            for ip in ips:
                lequips = []
                ip_maps = dict()
                ip_maps['id'] = ip.id
                ip_maps['block1'] = ip.block1
                ip_maps['block2'] = ip.block2
                ip_maps['block3'] = ip.block3
                ip_maps['block4'] = ip.block4
                ip_maps['block5'] = ip.block5
                ip_maps['block6'] = ip.block6
                ip_maps['block7'] = ip.block7
                ip_maps['block8'] = ip.block8
                ip_maps['descricao'] = ip.description
                for equip in mapa.get(ip.id):
                    equip = Equipamento.get_by_pk(equip.equipamento.id)
                    lequips.append(model_to_dict(equip))
                ip_maps['equipamento'] = lequips
                list_ips.append(ip_maps)

            network_map['ips'] = list_ips

            network_map
            # Return XML
            return self.response(dumps_networkapi(network_map))