コード例 #1
0
def insert_ip_equipment(ip_id, equip_id, user):
    '''Insere o relacionamento entre o IP e o equipamento.

    @param ip_id: Identificador do IP.
    @param equip_id: Identificador do equipamento.
    @param user: Usuário autenticado.   

    @return: O ip_equipamento criado.

    @raise IpError: Falha ao inserir.
    @raise EquipamentoNotFoundError: Equipamento não cadastrado.  
    @raise IpNotFoundError: Ip não cadastrado.
    @raise IpEquipamentoDuplicatedError: IP já cadastrado para o equipamento.
    @raise EquipamentoError: Falha ao pesquisar o equipamento.
    @raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.
    '''
    if not has_perm(user, AdminPermission.IPS, AdminPermission.WRITE_OPERATION,
                    None, equip_id, AdminPermission.EQUIP_WRITE_OPERATION):
        raise UserNotAuthorizedError(
            None, u'Usuário não tem permissão para executar a operação.')

    ip_equipment = IpEquipamento()
    ip_equipment.create(user, ip_id, equip_id)

    return ip_equipment
コード例 #2
0
def insert_ip_equipment(ip_id, equip_id, user):
    '''Insere o relacionamento entre o IP e o equipamento.

    @param ip_id: Identificador do IP.
    @param equip_id: Identificador do equipamento.
    @param user: Usuário autenticado.   

    @return: O ip_equipamento criado.

    @raise IpError: Falha ao inserir.
    @raise EquipamentoNotFoundError: Equipamento não cadastrado.  
    @raise IpNotFoundError: Ip não cadastrado.
    @raise IpEquipamentoDuplicatedError: IP já cadastrado para o equipamento.
    @raise EquipamentoError: Falha ao pesquisar o equipamento.
    @raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.
    '''
    if not has_perm(user,
                    AdminPermission.IPS,
                    AdminPermission.WRITE_OPERATION,
                    None,
                    equip_id,
                    AdminPermission.EQUIP_WRITE_OPERATION):
        raise UserNotAuthorizedError(
            None, u'Usuário não tem permissão para executar a operação.')

    ip_equipment = IpEquipamento()
    ip_equipment.create(user, ip_id, equip_id)

    return ip_equipment
コード例 #3
0
def buscar_ip(id_sw):

    ip_sw=None

    ips = IpEquipamento()
    ips = ips.list_by_equip(id_sw)

    for ip in ips:
        ip_sw = Ip.get_by_pk(ip.ip.id)

    if not ip_sw==None:
        ip_sw = str(ip_sw.oct1)+'.'+str(ip_sw.oct2)+'.'+str(ip_sw.oct3)+'.'+str(ip_sw.oct4)

    return ip_sw
コード例 #4
0
    def test_check_available_ip(self):
        ip_equipamento = IpEquipamento(equipamento=Equipamento(
            tipo_equipamento=TipoEquipamento(id=1,
                                             tipo_equipamento='balanceador')))
        network = self.mock_network(ip_equipamento)

        self.mock_user_has_permission(True)
        self.mock_get_vip_environment_by_pk(
            self.mock_vip_environment(1, 'production env', networks=[network]))
        self.mock_network_get_available_ip(IPv4Address('192.168.1.1'))
        self.mock_get_tipo_balanceador(
            TipoEquipamento(id=1, tipo_equipamento='balanceador'))
        ip_save_mock = self.mock_ip_save()

        response = self.client.post('/ip/availableip4/vip/1/',
                                    XML % 1,
                                    content_type='text/xml')

        print(response)
        xml_map = self.parse_response(response)
        self.assertEquals('192',
                          xml_map.get('networkapi').get('ip').get('oct1'))
        self.assertEquals('168',
                          xml_map.get('networkapi').get('ip').get('oct2'))
        self.assertEquals('1', xml_map.get('networkapi').get('ip').get('oct3'))
        self.assertEquals('1', xml_map.get('networkapi').get('ip').get('oct4'))
        self.assertEquals(200, response.status_code)
        self.assertTrue(ip_save_mock.called)
コード例 #5
0
def buscar_ip(id_sw):
    """Retuns switch IP that is registered in a management environment
    """

    ip_sw = None

    ips = IpEquipamento()
    ips_equip = ips.list_by_equip(id_sw)
    regexp = re.compile(r'GERENCIA')

    mgnt_ip = None
    for ip_equip in ips_equip:
        ip_sw = ip_equip.ip
        if ip_sw is not None:
            if regexp.search(ip_sw.networkipv4.vlan.ambiente.ambiente_logico.nome) is not None:
                mgnt_ip = str(ip_sw.oct1) + '.' + str(ip_sw.oct2) + \
                    '.' + str(ip_sw.oct3) + '.' + str(ip_sw.oct4)

    return mgnt_ip
コード例 #6
0
    def test_deploy_networkipv4_configuration_with_active_vlan(self):
        self.networkv4.vlan.ativada = True

        ipv4 = Ip(oct1=192, oct2=168, oct3=0, oct4=0)
        self.mock_ip_get_by_octets(ipv4)
        self.mock_find_equipamento_ip([IpEquipamento()])
        self.mock_dhcp_relay_find([DHCPRelayIPv4(ipv4=ipv4)])
        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_network_activation()
        vlan_activation_mock = self.mock_vlan_activation()

        response = deploy_networkIPv4_configuration(self.user, self.networkv4,
                                                    self.equipment_list)

        self.assertTrue(deploy_config_mock.called)
        network_activation_mock.assert_called_with(self.user)
        self.assertFalse(vlan_activation_mock.called)
        self.assertEquals({1: 'config_deployed'}, response)
コード例 #7
0
def remove_ip_equipment(ip_id, equipment_id, user):
    ''' Remove o relacionamento entre um ip e um equipamento.

    @param ip_id: Identificador do IP.
    @param equipment_id: Identificador do equipamento.
    @param user: Usuário autenticado.

    @return: Nothing.

    @raise IpEquipmentNotFoundError: Relacionamento não cadastrado. 
    @raise IpEquipCantDissociateFromVip: Equip is the last balancer in a created Vip Request, the relationship cannot be removed.
    @raise EquipamentoNotFoundError: Equipamento não cadastrado.
    @raise IpError, GrupoError: Falha na pesquisa dos dados ou na operação de remover.
    @raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.  
    '''
    if not has_perm(user, AdminPermission.IPS, AdminPermission.WRITE_OPERATION,
                    None, equipment_id, AdminPermission.EQUIP_WRITE_OPERATION):
        raise UserNotAuthorizedError(
            None, u'Usuário não tem permissão para executar a operação.')

    IpEquipamento().remove(user, ip_id, equipment_id)
    return
コード例 #8
0
    def test_check_available_ip_given_no_load_balancer_equipment_available_on_network(
            self):
        ip_equipamento = IpEquipamento(equipamento=Equipamento(
            tipo_equipamento=TipoEquipamento(id=2, tipo_equipamento='router')))
        network = self.mock_network(ip_equipamento)

        self.mock_user_has_permission(True)
        self.mock_get_vip_environment_by_pk(
            self.mock_vip_environment(1, 'production env', networks=[network]))
        self.mock_network_get_available_ip(IPv4Address('192.168.1.1'))
        self.mock_get_tipo_balanceador(
            TipoEquipamento(id=1, tipo_equipamento='balanceador'))

        response = self.client.post('/ip/availableip4/vip/1/',
                                    XML % 1,
                                    content_type='text/xml')

        xml_map = self.parse_response(response)
        self.assertEquals(
            'Não há ipv4 disponivel para as redes associdas com o Ambiente '
            'Vip: production env - production env - production env, pois não existe '
            'equipamentos do Tipo Balanceador nessas redes.',
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
コード例 #9
0
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IP to an equipment.

        URL: ipv4/assoc/
        '''

        self.log.info('Associate Ip 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_ipv4_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_ipv4_id
            if not is_valid_int_greater_zero_param(network_ipv4_id):
                self.log.error(
                    u'Parameter network_ipv4_id is invalid. Value: %s.', network_ipv4_id)
                raise InvalidValueError(
                    None, 'network_ipv4_id', network_ipv4_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 = NetworkIPv4.get_by_pk(network_ipv4_id)

            with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id):

                # Get ip
                ip = Ip.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)

                                #Equipment type should be in both filters
                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                                    #Out of band network is never trunked, it is only in mgmt interface
                                    # allow it - not a good thing to to, but is very specific
                                    if vlan.ambiente.divisao_dc.nome == 'OOB-CM' or vlan_atual.ambiente.divisao_dc.nome == 'OOB-CM':
                                        flag_vlan_error = False
                                        

                            ## 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 = IpEquipamento()
                        ipEquip.get_by_ip_equipment(ip.id, equip_id)

                        # Ip %s.%s.%s.%s already has association with
                        # Equipament %s.' % (self.oct1, self.oct2, self.oct3,
                        # self.oct4,equipment_id)
                        raise IpEquipmentAlreadyAssociation(None, u'Ip %s.%s.%s.%s already has association with Equipament %s.' % (
                            ip.oct1, ip.oct2, ip.oct3, ip.oct4, equip_id))
                    except IpEquipmentNotFoundError, e:
                        pass

                    equipment = Equipamento().get_by_pk(equip_id)
                    ip_equipment = IpEquipamento()
                    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 IpEquipamento related to this equipment
                    ip_equips = IpEquipamento.objects.filter(
                        equipamento=equip_id)

                    for ip_test in [ip_equip.ip for ip_equip in ip_equips]:
                        if ip_test.networkipv4.oct1 == ip.networkipv4.oct1 and \
                                ip_test.networkipv4.oct2 == ip.networkipv4.oct2 and \
                                ip_test.networkipv4.oct3 == ip.networkipv4.oct3 and \
                                ip_test.networkipv4.oct4 == ip.networkipv4.oct4 and \
                                ip_test.networkipv4.block == ip.networkipv4.block and \
                                ip_test.networkipv4 != ip.networkipv4:

                            # Filter testing
                            if ip_test.networkipv4.vlan.ambiente.filter is None or ip.networkipv4.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.networkipv4.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.networkipv4.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 ##

                    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)

                        # Delete vlan's cache
                        destroy_cache_function([net.vlan_id])
                    except EquipamentoAmbienteDuplicatedError, e:
                        # If already exists, OK !
                        pass

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
コード例 #10
0
    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)
コード例 #11
0
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to add an IP and associate it to an equipment.

        URL: ipv4/save/
        '''

        self.log.info('Add an IP 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_ipv4_id = ip_map.get('id_net')
            description = ip_map.get('descricao')
            ip4 = ip_map.get('ip4')

            # 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_ipv4_id):
                self.log.error(
                    u'Parameter network_ipv4_id is invalid. Value: %s.', network_ipv4_id)
                raise InvalidValueError(
                    None, 'network_ipv4_id', network_ipv4_id)

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

            # Description can NOT be greater than 100
            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
            ip = Ip()

            net = NetworkIPv4.get_by_pk(network_ipv4_id)

            with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id):

                # se Houver erro no ip informado para retorna-lo na mensagem
                ip_error = ip4

                # verificação se foi passado algo errado no ip
                ip4 = ip4.split(".")
                for oct in ip4:
                    if not is_valid_int_param(oct):
                        raise InvalidValueError(None, 'ip4', ip_error)
                        #raise IndexError

                # Ip passado de forma invalida
                if len(ip4) is not 4:
                    raise IndexError

                ip.descricao = description
                ip.oct1 = ip4[0]
                ip.oct2 = ip4[1]
                ip.oct3 = ip4[2]
                ip.oct4 = ip4[3]

                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
                ip.save_ipv4(equip_id, user, net)

                list_ip = []
                lequips = []

                if ip.id is None:
                    ip = Ip.get_by_octs_and_net(
                        ip.oct1, ip.oct2, ip.oct3, ip.oct4, net.id)

                equips = IpEquipamento.list_by_ip(ip.id)
                ip_maps = dict()
                ip_maps['id'] = ip.id
                ip_maps['oct1'] = ip.oct1
                ip_maps['oct2'] = ip.oct2
                ip_maps['oct3'] = ip.oct3
                ip_maps['oct4'] = ip.oct4
                ip_maps['descricao'] = ip.descricao

                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['ip'] = 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)
コード例 #12
0
    def administrate_real(self,
                          user,
                          vip_id,
                          equip_id,
                          ip_id,
                          operation,
                          network_version,
                          port_vip=None,
                          port_real=None):

        # 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 Equipament ID
        if not is_valid_int_greater_zero_param(equip_id):
            self.log.error(u'The equip_id parameter is not a valid value: %s.',
                           equip_id)
            raise InvalidValueError(None, 'equip_id', equip_id)

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

        # Valid operation
        if operation not in ['add', 'del', 'ena', 'dis', 'chk']:
            self.log.error(
                u'The operation parameter is not a valid value: %s.',
                operation)
            raise InvalidValueError(None, 'operation', operation)

        # Valid network version
        if network_version not in ['v4', 'v6']:
            self.log.error(
                u'The network_version parameter is not a valid value: %s.',
                network_version)
            raise InvalidValueError(None, 'network_version', network_version)

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

        # new_call = True - New calls for Add/Del/Enable/Disable/Check with new params (Port Vip and Port Real)
        # new_call = False = Old calls for compatibility
        new_call = False
        if port_vip is not None and port_real is not None:
            # Valid ports
            if not is_valid_int_greater_zero_param(port_vip):
                self.log.error(
                    u'The port_vip parameter is not a valid value: %s.',
                    port_vip)
                raise InvalidValueError(None, 'port_vip', port_vip)

            if not is_valid_int_greater_zero_param(port_real):
                self.log.error(
                    u'The port_vip parameter is not a valid value: %s.',
                    port_real)
                raise InvalidValueError(None, 'port_real', port_real)

            new_call = True

        # Find Request VIP by ID to check if it exist
        vip = RequisicaoVips.get_by_pk(vip_id)
        # Get variables
        variables_map = vip.variables_to_map()
        # Valid variables
        # vip.set_variables(variables_map)

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

        # Valid network_version - IPv4
        if network_version == IP_VERSION.IPv4[0]:

            # Find IpEquipamento to check if it exist
            IpEquip = IpEquipamento().get_by_ip_equipment(ip_id, equip_id)

            real_name = IpEquip.equipamento.nome
            end_ip = '%s.%s.%s.%s' % (IpEquip.ip.oct1, IpEquip.ip.oct2,
                                      IpEquip.ip.oct3, IpEquip.ip.oct4)

            # Valid Real
            RequisicaoVips.valid_real_server(end_ip, IpEquip.equipamento, evip,
                                             False)

        # Valid network_version - IPv6
        elif network_version == IP_VERSION.IPv6[0]:

            # Find Ipv6Equipament to check if it exist
            Ipv6Equip = Ipv6Equipament().get_by_ip_equipment(ip_id, equip_id)

            real_name = Ipv6Equip.equipamento.nome
            end_ip = '%s:%s:%s:%s:%s:%s:%s:%s' % (
                Ipv6Equip.ip.block1, Ipv6Equip.ip.block2, Ipv6Equip.ip.block3,
                Ipv6Equip.ip.block4, Ipv6Equip.ip.block5, Ipv6Equip.ip.block6,
                Ipv6Equip.ip.block7, Ipv6Equip.ip.block8)

            # Valid Real
            RequisicaoVips.valid_real_server(end_ip, Ipv6Equip.equipamento,
                                             evip, False)

        if (operation == 'chk'):

            if IP_VERSION.IPv4[0] == network_version:
                if new_call:
                    command = VIP_REALS_v4_CHECK % (vip_id, ip_id, port_real,
                                                    port_vip)
                else:
                    command = VIP_REAL_v4_CHECK % (vip_id, real_name, end_ip)
            else:
                if new_call:
                    command = VIP_REALS_v6_CHECK % (vip_id, ip_id, port_real,
                                                    port_vip)
                else:
                    command = VIP_REAL_v6_CHECK % (vip_id, real_name, end_ip)
        else:

            with distributedlock(LOCK_VIP_IP_EQUIP %
                                 (vip_id, ip_id, equip_id)):

                if (operation == 'add'):

                    if IP_VERSION.IPv4[0] == network_version:
                        if new_call:
                            command = VIP_REALS_v4_CREATE % (
                                vip_id, ip_id, port_real, port_vip)
                            ServerPoolMember().save_specified_port(
                                vip_id, port_vip, IpEquip.ip,
                                IP_VERSION.IPv4[1], port_real, user)
                        else:
                            command = VIP_REAL_v4_CREATE % (vip_id, real_name,
                                                            end_ip)
                            ServerPoolMember().save_with_default_port(
                                vip_id, IpEquip.ip, IP_VERSION.IPv4[1], user)

                    else:
                        if new_call:
                            command = VIP_REALS_v6_CREATE % (
                                vip_id, ip_id, port_real, port_vip)
                            ServerPoolMember().save_specified_port(
                                vip_id, port_vip, Ipv6Equip.ip,
                                IP_VERSION.IPv6[1], port_real, user)
                        else:
                            command = VIP_REAL_v6_CREATE % (vip_id, real_name,
                                                            end_ip)
                            ServerPoolMember().save_with_default_port(
                                vip_id, Ipv6Equip.ip, IP_VERSION.IPv6[1], user)

                elif (operation == 'del'):

                    if IP_VERSION.IPv4[0] == network_version:
                        if new_call:
                            command = VIP_REALS_v4_REMOVE % (
                                vip_id, ip_id, port_real, port_vip)
                            pool_members = ServerPoolMember.objects.filter(
                                ip=ip_id,
                                server_pool__vipporttopool__requisicao_vip__id=
                                vip_id,
                                server_pool__vipporttopool__port_vip=port_vip,
                                port_real=port_real)
                            [
                                pool_member.delete()
                                for pool_member in pool_members
                            ]
                        else:
                            command = VIP_REAL_v4_REMOVE % (vip_id, real_name,
                                                            end_ip)
                            pool_members = ServerPoolMember.objects.filter(
                                ip=ip_id,
                                server_pool__vipporttopool__requisicao_vip__id=
                                vip_id)
                            [
                                pool_member.delete()
                                for pool_member in pool_members
                            ]
                    else:
                        if new_call:
                            command = VIP_REALS_v6_REMOVE % (
                                vip_id, ip_id, port_real, port_vip)
                            pool_members = ServerPoolMember.objects.filter(
                                ipv6=ip_id,
                                server_pool__vipporttopool__requisicao_vip__id=
                                vip_id,
                                server_pool__vipporttopool__port_vip=port_vip,
                                port_real=port_real)
                            [
                                pool_member.delete()
                                for pool_member in pool_members
                            ]
                        else:
                            command = VIP_REAL_v6_REMOVE % (vip_id, real_name,
                                                            end_ip)
                            pool_members = ServerPoolMember.objects.filter(
                                ipv6=ip_id,
                                server_pool__vipporttopool__requisicao_vip__id=
                                vip_id)
                            [
                                pool_member.delete()
                                for pool_member in pool_members
                            ]

                elif (operation == 'ena'):

                    if IP_VERSION.IPv4[0] == network_version:
                        if new_call:
                            command = VIP_REALS_v4_ENABLE % (
                                vip_id, ip_id, port_real, port_vip)
                        else:
                            command = VIP_REAL_v4_ENABLE % (vip_id, real_name,
                                                            end_ip)
                    else:
                        if new_call:
                            command = VIP_REALS_v6_ENABLE % (
                                vip_id, ip_id, port_real, port_vip)
                        else:
                            command = VIP_REAL_v6_ENABLE % (vip_id, real_name,
                                                            end_ip)

                elif (operation == 'dis'):

                    if IP_VERSION.IPv4[0] == network_version:
                        if new_call:
                            command = VIP_REALS_v4_DISABLE % (
                                vip_id, ip_id, port_real, port_vip)
                        else:
                            command = VIP_REAL_v4_DISABLE % (vip_id, real_name,
                                                             end_ip)
                    else:
                        if new_call:
                            command = VIP_REALS_v6_DISABLE % (
                                vip_id, ip_id, port_real, port_vip)
                        else:
                            command = VIP_REAL_v6_DISABLE % (vip_id, real_name,
                                                             end_ip)

        self.log.info(command)
        # Execute script
        code, stdout, stderr = exec_script(command)
        self.log.info(stdout)

        map = dict()
        success_map = dict()

        # Return XML
        if code == 0:
            success_map['codigo'] = '%04d' % code
            success_map['descricao'] = {'stdout': stdout, 'stderr': stderr}

            map['sucesso'] = success_map
            return self.response(dumps_networkapi(map))

        elif code == 12:
            success_map['codigo'] = '0'
            success_map['descricao'] = {'stdout': '0', 'stderr': ''}

            map['sucesso'] = success_map
            self.rollback_changes(operation, new_call, network_version, vip_id,
                                  ip_id, port_real, port_vip, real_name,
                                  end_ip, user)
            return self.response(dumps_networkapi(map))

        else:
            self.rollback_changes(operation, new_call, network_version, vip_id,
                                  ip_id, port_real, port_vip, real_name,
                                  end_ip, user)
            return self.response_error(2, stdout + stderr)
コード例 #13
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4.

        URLs: ip/get/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 = Ip()

            ip = ip.get_by_pk(id_ip)

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

            try:

                EquipIps = []
                equipsIp = IpEquipamento.list_by_ip(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['oct1'] = ip.oct1
            ip_maps['oct2'] = ip.oct2
            ip_maps['oct3'] = ip.oct3
            ip_maps['oct4'] = ip.oct4
            ip_maps['descricao'] = ip.descricao
            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)
コード例 #14
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4.

        URLs: ip/get/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 = Ip()

            ip = ip.get_by_pk(id_ip)

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

            try:

                EquipIps = []
                equipsIp = IpEquipamento.list_by_ip(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['oct1'] = ip.oct1
            ip_maps['oct2'] = ip.oct2
            ip_maps['oct3'] = ip.oct3
            ip_maps['oct4'] = ip.oct4
            ip_maps['descricao'] = ip.descricao
            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 GET requests get an IP4 available for vip_request by evip_id.

        URL: ip/availableip6/vip/id_evip/
        '''

        self.log.info('Get an IP4 available for vip_request')

        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()

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

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            ip_map = networkapi_map.get('ip_map')

            # Get XML data
            id_evip = ip_map.get('id_evip')
            name = ip_map.get('name')

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

            # Business Rules
            evip = EnvironmentVip.get_by_pk(id_evip)

            with distributedlock(LOCK_GET_IPV4_AVAILABLE % id_evip):
                ipv4 = Ip()

                len_network = len(evip.networkipv4_set.all())
                raise_not_found_balanceamento = False

                if (len_network <= 0):
                    raise NetworkNotInEvip(None, 'Não há rede no ambiente vip fornecido')

                cont_network = 0
                cont_balanceador_not_found = 0

                for net in evip.networkipv4_set.all():

                    balanceador_found_flag = False
                    cont_network = cont_network + 1
                    list_ips_equips = list()

                    try:
                        ip_available = ipv4.get_available_ip(net.id)
                        ip_new = Ip()
                        ip_available = ip_available.exploded
                        ip_available = ip_available.split(".")
                        ip_new.oct1 = ip_available[0]
                        ip_new.oct2 = ip_available[1]
                        ip_new.oct3 = ip_available[2]
                        ip_new.oct4 = ip_available[3]
                        ip_new.descricao = name

                        for env_equipment in net.vlan.ambiente.equipamentoambiente_set.all():
                            equipment = env_equipment.equipamento
                            if equipment.tipo_equipamento == TipoEquipamento.get_tipo_balanceador():

                                if equipment.id not in list_ips_equips:

                                    list_ips_equips.append(equipment.id)

                                    if ip_new.id is None:
                                        ip_new.save_ipv4(equipment.id, user, net)
                                    else:
                                        new_ip_equip = IpEquipamento()
                                        new_ip_equip.ip = ip_new
                                        new_ip_equip.equipamento = equipment
                                        new_ip_equip.save()

                                    balanceador_found_flag = True

                        if not balanceador_found_flag:
                            cont_balanceador_not_found = cont_balanceador_not_found + 1
                        else:
                            break

                        if cont_balanceador_not_found == len_network:
                            raise_not_found_balanceamento = True
                            raise IpNotAvailableError(None, "Não há ipv4 disponivel para as redes associdas com o Ambiente "
                                                            "Vip: %s - %s - %s, pois não existe equipamentos do Tipo "
                                                            "Balanceador nessas redes."
                                                      % (evip.finalidade_txt, evip.cliente_txt, evip.ambiente_p44_txt))

                    except (IpNotAvailableError, IpRangeAlreadyAssociation), e:
                        cont_balanceador_not_found = cont_balanceador_not_found + 1
                        if raise_not_found_balanceamento:
                            raise IpNotAvailableError(None, e.message)
                        elif len_network == cont_network:
                            raise IpNotAvailableError(None, "Não há ipv4 disponivel para as redes associdas com o Ambiente "
                                                            "Vip: %s - %s - %s"
                                                      % (evip.finalidade_txt, evip.cliente_txt, evip.ambiente_p44_txt))

                transaction.commit()

                return self.response(dumps_networkapi({"ip": model_to_dict(ip_new)}))

        except NetworkNotInEvip, e:
            return self.response_error(321, 'ipv4')
コード例 #16
0
    def network_ipv4_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 NetworkIPv4
            network_ipv4 = NetworkIPv4()
            vlan_map = network_ipv4.add_network_ipv4(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 ipv4 on all equipment
                # that is configured as a router for the environment related to
                # network
                ip = Ip.get_first_available_ip(vlan_map['vlan']['id_network'])

                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()

                if len(list_equip_routers_ambient) > 1:
                    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(
                            vlan_map['vlan']['id_network'], 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 = vlan_map['vlan'][
                            'id_network']
                        ip_model2.save()
                        IpEquipamento().create(user, ip_model2.id,
                                               equip.equipamento.id)

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
コード例 #17
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv4 by network ipv4 id.

        URLs: ip/id_network_ipv4/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

            NetworkIPv4.get_by_pk(id_network)

            ips = Ip.list_by_network(id_network)

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

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

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

            try:
                for ip in ips:
                    EquipIps = []
                    equipsIp = IpEquipamento.list_by_ip(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 = []

            for ip in ips:
                lequips = []
                ip_maps = dict()
                ip_maps = model_to_dict(ip)

                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

            # Return XML
            return self.response(dumps_networkapi(network_map))
コード例 #18
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)
コード例 #19
0
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles GET requests get an IP4 available for vip_request by evip_id.

        URL: ip/availableip6/vip/id_evip/
        '''

        self.log.info('Get an IP4 available for vip_request')

        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()

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

            # XML data format
            networkapi_map = xml_map.get('networkapi')

            ip_map = networkapi_map.get('ip_map')

            # Get XML data
            id_evip = ip_map.get('id_evip')
            name = ip_map.get('name')

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

            # Business Rules
            evip = EnvironmentVip.get_by_pk(id_evip)

            ipv4 = Ip()

            len_network = len(evip.networkipv4_set.all())
            raise_not_found_balanceamento = False

            if (len_network <= 0):
                raise NetworkNotInEvip(
                    None, 'Não há rede no ambiente vip fornecido')

            cont_network = 0
            cont_balanceador_not_found = 0

            for net in evip.networkipv4_set.all():

                balanceador_found_flag = False
                cont_network = cont_network + 1
                list_ips_equips = list()

                try:
                    ip_available = ipv4.get_available_ip(net.id)

                    ip_new = Ip()
                    ip_available = ip_available.exploded
                    ip_available = ip_available.split(".")
                    ip_new.oct1 = ip_available[0]
                    ip_new.oct2 = ip_available[1]
                    ip_new.oct3 = ip_available[2]
                    ip_new.oct4 = ip_available[3]
                    ip_new.descricao = name

                    for env_equipment in net.vlan.ambiente.equipamentoambiente_set.all():
                        equipment = env_equipment.equipamento
                        if equipment.tipo_equipamento == TipoEquipamento.get_tipo_balanceador():

                            if equipment.id not in list_ips_equips:

                                list_ips_equips.append(equipment.id)

                                if ip_new.id is None:
                                    ip_new.save_ipv4(equipment.id, user, net)
                                else:
                                    new_ip_equip = IpEquipamento()
                                    new_ip_equip.ip = ip_new
                                    new_ip_equip.equipamento = equipment
                                    new_ip_equip.save(user)

                                balanceador_found_flag = True

                    if not balanceador_found_flag:
                        cont_balanceador_not_found = cont_balanceador_not_found + \
                            1
                    else:
                        break

                    if cont_balanceador_not_found == len_network:
                        raise_not_found_balanceamento = True
                        raise IpNotAvailableError(None, "Não há ipv4 disponivel para as redes associdas com o Ambiente Vip: %s - %s - %s, pois não existe equipamentos do Tipo Balanceador nessas redes." % (
                            evip.finalidade_txt, evip.cliente_txt, evip.ambiente_p44_txt))

                except (IpNotAvailableError, IpRangeAlreadyAssociation), e:
                    cont_balanceador_not_found = cont_balanceador_not_found + 1
                    if raise_not_found_balanceamento:
                        raise IpNotAvailableError(None, e.message)
                    elif len_network == cont_network:
                        raise IpNotAvailableError(None, "Não há ipv4 disponivel para as redes associdas com o Ambiente Vip: %s - %s - %s" % (
                            evip.finalidade_txt, evip.cliente_txt, evip.ambiente_p44_txt))

            return self.response(dumps_networkapi({"ip": model_to_dict(ip_new)}))
コード例 #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)
コード例 #21
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to list all network IPv4 by network ipv4 id.

        URLs: ip/id_network_ipv4/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

            NetworkIPv4.get_by_pk(id_network)

            ips = Ip.list_by_network(id_network)

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

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

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

            try:
                for ip in ips:
                    EquipIps = []
                    equipsIp = IpEquipamento.list_by_ip(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 = []

            for ip in ips:
                lequips = []
                ip_maps = dict()
                ip_maps = model_to_dict(ip)

                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

            # Return XML
            return self.response(dumps_networkapi(network_map))
コード例 #22
0
    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 add an IP and associate it to an equipment.

        URL: ipv4/save/
        '''

        self.log.info('Add an IP 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_ipv4_id = ip_map.get('id_net')
            description = ip_map.get('descricao')
            ip4 = ip_map.get('ip4')

            # 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_ipv4_id):
                self.log.error(
                    u'Parameter network_ipv4_id is invalid. Value: %s.',
                    network_ipv4_id)
                raise InvalidValueError(None, 'network_ipv4_id',
                                        network_ipv4_id)

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

            # Description can NOT be greater than 100
            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
            ip = Ip()

            net = NetworkIPv4.get_by_pk(network_ipv4_id)

            with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id):

                # se Houver erro no ip informado para retorna-lo na mensagem
                ip_error = ip4

                # verificação se foi passado algo errado no ip
                ip4 = ip4.split(".")
                for oct in ip4:
                    if not is_valid_int_param(oct):
                        raise InvalidValueError(None, 'ip4', ip_error)
                        #raise IndexError

                # Ip passado de forma invalida
                if len(ip4) is not 4:
                    raise IndexError

                ip.descricao = description
                ip.oct1 = ip4[0]
                ip.oct2 = ip4[1]
                ip.oct3 = ip4[2]
                ip.oct4 = ip4[3]

                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
                ip.save_ipv4(equip_id, user, net)

                list_ip = []
                lequips = []

                if ip.id is None:
                    ip = Ip.get_by_octs_and_net(ip.oct1, ip.oct2, ip.oct3,
                                                ip.oct4, net.id)

                equips = IpEquipamento.list_by_ip(ip.id)
                ip_maps = dict()
                ip_maps['id'] = ip.id
                ip_maps['oct1'] = ip.oct1
                ip_maps['oct2'] = ip.oct2
                ip_maps['oct3'] = ip.oct3
                ip_maps['oct4'] = ip.oct4
                ip_maps['descricao'] = ip.descricao

                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['ip'] = 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)
コード例 #24
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)
コード例 #25
0
    def network_ipv4_add(self,
                         user,
                         vlan_id,
                         network_type,
                         environment_vip,
                         prefix=None):

        try:

            if not is_valid_int_greater_zero_param(vlan_id):
                msg = "The Vlan number is invalid. Value: {}".format(prefix)
                self.log.error(msg)
                return self.response_error(150, msg)

            net = None
            if network_type:
                net = TipoRede.get_by_pk(network_type)

            if environment_vip is not None:
                # Valid environment_vip ID
                if not is_valid_int_greater_zero_param(environment_vip):
                    msg = "The VIP Environment id is invalid. Value: {}".format(
                        prefix)
                    self.log.error(msg)
                    return self.response_error(150, msg)
                # Find Environment VIP by ID to check if it exist
                evip = EnvironmentVip.get_by_pk(environment_vip)

            else:
                evip = None

            # Business Rules

            # New NetworkIPv4
            network_ipv4 = NetworkIPv4()
            vlan_map = network_ipv4.add_network_ipv4(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 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(vlan_map['vlan']['id_network'])

                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()

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

                if vlan_map.get('vlan').get('vxlan'):

                    logging.debug('vxlan')
                    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_ipv4.id, True)

                        ips = Ip()
                        ips.oct1, ips.oct2, ips.oct3, ips.oct4 = str(
                            debug_ip).split('.')
                        ips.networkipv4_id = network_ipv4.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_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)

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)