def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir um tipo de rede

        URL: /tiporede/<id_tipo_rede>/ 

        """

        # Verifica acesso e obtém dados do request
        try:
            # Verificar a permissão
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            # Obtém argumentos passados na URL
            id_tipo_rede = kwargs.get('id_tipo_rede')
            if id_tipo_rede is None:
                return self.response_error(256)

            # Remove a informação de acesso a equipamento
            TipoRede.remove(user, id_tipo_rede)

            # Retorna response vazio em caso de sucesso
            return self.response(dumps_networkapi({}))
        except TipoRedeNotFoundError:
            return self.response_error(111)
        except TipoRedeUsedByVlanError:
            return self.response_error(215, id_tipo_rede)
        except (GrupoError, VlanError):
            return self.response_error(1)
def config_ambiente(user, hosts, ambientes):
    #ip_config
    ip_config = IPConfig()
    ip_config.subnet = hosts.get("REDE")
    ip_config.new_prefix = hosts.get("PREFIX")
    if hosts.get("VERSION")=="ipv4":
        ip_config.type = IP_VERSION.IPv4[0]
    elif hosts.get("VERSION")=="ipv6":
        ip_config.type = IP_VERSION.IPv6[0]
    tiporede = TipoRede()
    tipo = tiporede.get_by_name(hosts.get("TIPO"))
    ip_config.network_type = tipo

    ip_config.save()

    #ambiente
    config_environment = ConfigEnvironment()
    amb_log = AmbienteLogico()
    div = DivisaoDc()
    amb_log = amb_log.get_by_name(ambientes.get("LOG"))
    div = div.get_by_name(ambientes.get("DC"))
    for j in Ambiente().search(div.id, amb_log.id):
        if j.grupo_l3.nome==ambientes.get("L3"):
            config_environment.environment = j
            
    config_environment.ip_config = ip_config

    config_environment.save()
def config_ambiente(user, hosts, ambientes):
    #ip_config
    ip_config = IPConfig()
    ip_config.subnet = hosts.get("REDE")
    ip_config.new_prefix = hosts.get("PREFIX")
    if hosts.get("VERSION") == "ipv4":
        ip_config.type = IP_VERSION.IPv4[0]
    elif hosts.get("VERSION") == "ipv6":
        ip_config.type = IP_VERSION.IPv6[0]
    tiporede = TipoRede()
    tipo = tiporede.get_by_name(hosts.get("TIPO"))
    ip_config.network_type = tipo

    ip_config.save()

    #ambiente
    config_environment = ConfigEnvironment()
    amb_log = AmbienteLogico()
    div = DivisaoDc()
    amb_log = amb_log.get_by_name(ambientes.get("LOG"))
    div = div.get_by_name(ambientes.get("DC"))
    for j in Ambiente().search(div.id, amb_log.id):
        if j.grupo_l3.nome == ambientes.get("L3"):
            config_environment.environment = j

    config_environment.ip_config = ip_config

    config_environment.save()
Пример #4
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir um tipo de rede

        URL: /tiporede/<id_tipo_rede>/ 

        """

        # Verifica acesso e obtém dados do request
        try:
            # Verificar a permissão
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            # Obtém argumentos passados na URL
            id_tipo_rede = kwargs.get('id_tipo_rede')
            if id_tipo_rede is None:
                return self.response_error(256)

            # Remove a informação de acesso a equipamento
            TipoRede.remove(user, id_tipo_rede)

            # Retorna response vazio em caso de sucesso
            return self.response(dumps_networkapi({}))
        except TipoRedeNotFoundError:
            return self.response_error(111)
        except TipoRedeUsedByVlanError:
            return self.response_error(215, id_tipo_rede)
        except (GrupoError, VlanError):
            return self.response_error(1)
Пример #5
0
def config_ambiente(user, hosts, ambientes):
    # ip_config
    ip_config = IPConfig()
    ip_config.subnet = hosts.get('REDE')
    ip_config.new_prefix = hosts.get('PREFIX')
    if hosts.get('VERSION') == 'ipv4':
        ip_config.type = IP_VERSION.IPv4[0]
    elif hosts.get('VERSION') == 'ipv6':
        ip_config.type = IP_VERSION.IPv6[0]
    tiporede = TipoRede()
    tipo = tiporede.get_by_name(hosts.get('TIPO'))
    ip_config.network_type = tipo

    ip_config.save()

    # ambiente
    config_environment = ConfigEnvironment()
    amb_log = AmbienteLogico()
    div = DivisaoDc()
    amb_log = amb_log.get_by_name(ambientes.get('LOG'))
    div = div.get_by_name(ambientes.get('DC'))
    for j in Ambiente().search(div.id, amb_log.id):
        if j.grupo_l3.nome == ambientes.get('L3'):
            config_environment.environment = j

    config_environment.ip_config = ip_config

    config_environment.save()
Пример #6
0
    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para criar tipos de rede.

        URL: /tiporede/ 

        """

        # Obtém dados do request e verifica acesso
        try:
            # Verificar a permissão
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            # Obtém os dados do xml do request
            xml_map, attrs_map = loads(request.raw_post_data)

            # Obtém o mapa correspondente ao root node do mapa do XML
            # (networkapi)
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag networkapi do XML de requisição.'
                )

            # Verifica a existência do node "tipo_rede"
            tipo_rede_map = networkapi_map.get('tipo_rede')
            if tipo_rede_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag tipo_rede do XML de requisição.'
                )

            # Verifica a existência do valor "fqdn"
            nome = tipo_rede_map.get('nome')
            if nome is None:
                return self.response_error(176)

            # Cria acesso ao equipamento conforme dados recebidos no XML
            tipo_rede = TipoRede(tipo_rede=nome)
            tipo_rede.create(user)

            # Monta dict para response
            networkapi_map = dict()
            tipo_rede_map = dict()

            tipo_rede_map['id'] = tipo_rede.id
            networkapi_map['tipo_rede'] = tipo_rede_map

            return self.response(dumps_networkapi(networkapi_map))
        except TipoRedeNameDuplicatedError:
            return self.response_error(253, nome)
        except XMLError, x:
            self.log.error(u'Erro ao ler o XML da requisição.')
            return self.response_error(3, x)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new network types.

        URL: /net_type/ 

        """

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

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

            # Get networkapi tag map
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no networkapi tag from request XML.')

            # Get net_type tag map
            net_type_map = networkapi_map.get('net_type')
            if net_type_map is None:
                return self.response_error(3, u'There is no tipo_rede tag from request XML.')

            # Valid name attribute
            name = net_type_map.get('name')
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100):
                self.log.error(
                    u'Parameter %s is invalid. Value: %s.', 'name', name)
                raise InvalidValueError(None, 'name', name)

            net_type = TipoRede(tipo_rede=name)

            try:
                TipoRede.get_by_name(net_type.tipo_rede)
                raise NetworkTypeNameDuplicatedError(
                    None, u'Network type with name %s already exist' % net_type.tipo_rede)
            except NetworkTypeNotFoundError:
                pass

            try:
                net_type.save(user)
            except Exception, e:
                self.log.error(u'Failed to insert network type.')
                raise VlanError(e, u'Failed to insert network type.')

            net_type_map = dict()
            net_type_map['id'] = net_type.id

            return self.response(dumps_networkapi({'net_type': net_type_map}))
Пример #8
0
    def handle_put(self, request, user, *args, **kwargs):
        """Trata uma requisição PUT para alterar tipos de rede.

        URL: /tiporede/<id_tipo_rede>/ 

        """

        # Obtém dados do request e verifica acesso
        try:
            # Verificar a permissão
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            # Obtém argumentos passados na URL
            id_tipo_rede = kwargs.get('id_tipo_rede')
            if id_tipo_rede is None:
                return self.response_error(256)

            # Obtém dados do XML
            xml_map, attrs_map = loads(request.raw_post_data)

            # Obtém o mapa correspondente ao root node do mapa do XML
            # (networkapi)
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag networkapi do XML de requisição.'
                )

            # Verifica a existência do node "tipo_rede"
            tipo_rede_map = networkapi_map.get('tipo_rede')
            if tipo_rede_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag tipo_rede do XML de requisição.'
                )

            # Verifica a existência do valor "fqdn"
            nome = tipo_rede_map.get('nome')
            if nome is None:
                return self.response_error(176)

            # Altera o tipo de redeconforme dados recebidos no XML
            TipoRede.update(user, id_tipo_rede, tipo_rede=nome)

            # Retorna response vazio em caso de sucesso
            return self.response(dumps_networkapi({}))
        except XMLError, x:
            self.log.error(u'Erro ao ler o XML da requisição.')
            return self.response_error(3, x)
    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para criar tipos de rede.

        URL: /tiporede/ 

        """

        # Obtém dados do request e verifica acesso
        try:
            # Verificar a permissão
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            # Obtém os dados do xml do request
            xml_map, attrs_map = loads(request.raw_post_data)

            # Obtém o mapa correspondente ao root node do mapa do XML
            # (networkapi)
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')

            # Verifica a existência do node "tipo_rede"
            tipo_rede_map = networkapi_map.get('tipo_rede')
            if tipo_rede_map is None:
                return self.response_error(3, u'Não existe valor para a tag tipo_rede do XML de requisição.')

            # Verifica a existência do valor "fqdn"
            nome = tipo_rede_map.get('nome')
            if nome is None:
                return self.response_error(176)

            # Cria acesso ao equipamento conforme dados recebidos no XML
            tipo_rede = TipoRede(tipo_rede=nome)
            tipo_rede.create(user)

            # Monta dict para response
            networkapi_map = dict()
            tipo_rede_map = dict()

            tipo_rede_map['id'] = tipo_rede.id
            networkapi_map['tipo_rede'] = tipo_rede_map

            return self.response(dumps_networkapi(networkapi_map))
        except TipoRedeNameDuplicatedError:
            return self.response_error(253, nome)
        except XMLError, x:
            self.log.error(u'Erro ao ler o XML da requisição.')
            return self.response_error(3, x)
    def handle_put(self, request, user, *args, **kwargs):
        """Trata uma requisição PUT para alterar tipos de rede.

        URL: /tiporede/<id_tipo_rede>/ 

        """

        # Obtém dados do request e verifica acesso
        try:
            # Verificar a permissão
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            # Obtém argumentos passados na URL
            id_tipo_rede = kwargs.get('id_tipo_rede')
            if id_tipo_rede is None:
                return self.response_error(256)

            # Obtém dados do XML
            xml_map, attrs_map = loads(request.raw_post_data)

            # Obtém o mapa correspondente ao root node do mapa do XML
            # (networkapi)
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')

            # Verifica a existência do node "tipo_rede"
            tipo_rede_map = networkapi_map.get('tipo_rede')
            if tipo_rede_map is None:
                return self.response_error(3, u'Não existe valor para a tag tipo_rede do XML de requisição.')

            # Verifica a existência do valor "fqdn"
            nome = tipo_rede_map.get('nome')
            if nome is None:
                return self.response_error(176)

            # Altera o tipo de redeconforme dados recebidos no XML
            TipoRede.update(user,
                            id_tipo_rede,
                            tipo_rede=nome
                            )

            # Retorna response vazio em caso de sucesso
            return self.response(dumps_networkapi({}))
        except XMLError, x:
            self.log.error(u'Erro ao ler o XML da requisição.')
            return self.response_error(3, x)
Пример #11
0
    def test_alter_valid(self):
        mock = self.mock_valid_alter()
        response = self.alter(self.ID_ALTER_VALID, {self.XML_KEY: mock})
        valid_response(response)

        nt = TipoRede.get_by_pk(self.ID_ALTER_VALID)
        self.valid_attr(mock, model_to_dict(nt))
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições GET para consulta de tipos de rede.

        Permite a consulta de tipos de rede existentes.

        URL: /tiporede/ 
        """

        try:
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.READ_OPERATION):
                return self.not_authorized()

            # Efetua a consulta de todos os tipos de rede
            results = TipoRede.search()

            if results.count() > 0:
                # Monta lista com dados retornados
                map_list = []
                for item in results:
                    item_map = self.get_tipo_rede_map(item)
                    map_list.append(item_map)

                # Gera response (XML) com resultados
                return self.response(dumps_networkapi({'tipo_rede': map_list}))
            else:
                # Gera response (XML) para resultado vazio
                return self.response(dumps_networkapi({}))

        except (VlanError, GrupoError):
            return self.response_error(1)
Пример #13
0
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições GET para consulta de tipos de rede.

        Permite a consulta de tipos de rede existentes.

        URL: /tiporede/ 
        """

        try:
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            # Efetua a consulta de todos os tipos de rede
            results = TipoRede.search()

            if results.count() > 0:
                # Monta lista com dados retornados
                map_list = []
                for item in results:
                    item_map = self.get_tipo_rede_map(item)
                    map_list.append(item_map)

                # Gera response (XML) com resultados
                return self.response(dumps_networkapi({'tipo_rede': map_list}))
            else:
                # Gera response (XML) para resultado vazio
                return self.response(dumps_networkapi({}))

        except (VlanError, GrupoError):
            return self.response_error(1)
Пример #14
0
    def test_save_valid(self):
        mock = self.mock_valid()
        response = self.save({self.XML_KEY: mock})
        valid_response(response)
        content = valid_content(response, self.XML_KEY)

        nt = TipoRede.get_by_pk(content["id"])
        self.valid_attr(mock, model_to_dict(nt))
    def setUp(self):
        self.user = Usuario()
        self.vlan = Vlan(id=1, ambiente=Ambiente(id=1))
        self.network_type = TipoRede(id=1)
        self.vip_env = EnvironmentVip(id=1)
        self.network = NetworkIPv4(oct1=10, oct2=126, oct3=1, oct4=0, block=24)

        self.mock_distributed_lock()
        self.mock_transaction()
Пример #16
0
def criar_rede_ipv6(user, tipo_rede, variablestochangecore1, vlan, active=1):

    tiporede = TipoRede()
    net_id = tiporede.get_by_name(tipo_rede)
    network_type = tiporede.get_by_pk(net_id.id)

    network_ip = NetworkIPv6()
    network_ip.vlan = vlan
    network_ip.network_type = network_type
    network_ip.ambient_vip = None
    network_ip.active = active
    network_ip.block = variablestochangecore1.get('REDE_MASK')

    while str(variablestochangecore1.get('REDE_IP')).endswith(':'):
        variablestochangecore1['REDE_IP'] = variablestochangecore1[
            'REDE_IP'][:-1]

    while str(variablestochangecore1.get('NETMASK')).endswith(':'):
        variablestochangecore1['NETMASK'] = variablestochangecore1[
            'NETMASK'][:-1]

    len_ip_ipv6 = len(str(variablestochangecore1.get('REDE_IP')).split(':'))
    len_mask = len(str(variablestochangecore1.get('NETMASK')).split(':'))

    while (8 - len_ip_ipv6 > 0):  # 8-6=2--8-7=1--8-8=0
        len_ip_ipv6 = len_ip_ipv6 + 1
        variablestochangecore1['REDE_IP'] = variablestochangecore1.get(
            'REDE_IP') + ':0'

    while (8 - len_mask > 0):
        len_mask = len_mask + 1
        variablestochangecore1['NETMASK'] = variablestochangecore1.get(
            'NETMASK') + ':0'

    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(
        variablestochangecore1.get('REDE_IP')).split(':')
    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(
        variablestochangecore1.get('NETMASK')).split(':')

    destroy_cache_function([vlan.id])
    network_ip.save()

    return network_ip
def criar_rede(user, tipo_rede, variablestochangecore1, vlan, active=1):

    tiporede = TipoRede()
    net_id = tiporede.get_by_name(tipo_rede)
    network_type = tiporede.get_by_pk(net_id.id)

    network_ip = NetworkIPv4()
    network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str(variablestochangecore1.get("REDE_IP")).split('.')
    network_ip.block = variablestochangecore1.get("REDE_MASK")
    network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = str(variablestochangecore1.get("NETMASK")).split('.')
    network_ip.broadcast = variablestochangecore1.get("BROADCAST")
    network_ip.vlan = vlan
    network_ip.network_type = network_type
    network_ip.ambient_vip = None
    network_ip.active = active

    destroy_cache_function([vlan.id])
    network_ip.save()
 
    return network_ip
Пример #18
0
def criar_rede(user, tipo_rede, variablestochangecore1, vlan, active=1):

    tiporede = TipoRede()
    net_id = tiporede.get_by_name(tipo_rede)
    network_type = tiporede.get_by_pk(net_id.id)

    network_ip = NetworkIPv4()
    network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str(
        variablestochangecore1.get('REDE_IP')).split('.')
    network_ip.block = variablestochangecore1.get('REDE_MASK')
    network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = str(
        variablestochangecore1.get('NETMASK')).split('.')
    network_ip.broadcast = variablestochangecore1.get('BROADCAST')
    network_ip.vlan = vlan
    network_ip.network_type = network_type
    network_ip.ambient_vip = None
    network_ip.active = active

    destroy_cache_function([vlan.id])
    network_ip.save()

    return network_ip
Пример #19
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new network types.

        URL: /net_type/

        """

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

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

            # Get networkapi tag map
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no networkapi tag from request XML.')

            # Get net_type tag map
            net_type_map = networkapi_map.get('net_type')
            if net_type_map is None:
                return self.response_error(3, u'There is no tipo_rede tag from request XML.')

            # Valid name attribute
            name = net_type_map.get('name')
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100):
                self.log.error(
                    u'Parameter %s is invalid. Value: %s.', 'name', name)
                raise InvalidValueError(None, 'name', name)

            net_type = TipoRede(tipo_rede=name)

            if not is_valid_vlan_name(name):
                self.log.error(
                    u'Parameter %s is invalid because is using special characters and/or breaklines.', name)
                raise InvalidValueError(None, 'name', name)

            try:
                TipoRede.get_by_name(net_type.tipo_rede)
                raise NetworkTypeNameDuplicatedError(
                    None, u'Network type with name %s already exist' % net_type.tipo_rede)
            except NetworkTypeNotFoundError:
                pass

            try:
                net_type.save()
            except Exception, e:
                self.log.error(u'Failed to insert network type.')
                raise VlanError(e, u'Failed to insert network type.')

            net_type_map = dict()
            net_type_map['id'] = net_type.id

            return self.response(dumps_networkapi({'net_type': net_type_map}))
def criar_rede_ipv6(user, tipo_rede, variablestochangecore1, vlan, active=1):

    tiporede = TipoRede()
    net_id = tiporede.get_by_name(tipo_rede)
    network_type = tiporede.get_by_pk(net_id.id)

    network_ip = NetworkIPv6()
    network_ip.vlan = vlan
    network_ip.network_type = network_type
    network_ip.ambient_vip = None
    network_ip.active = active
    network_ip.block = variablestochangecore1.get("REDE_MASK")
    
    while str(variablestochangecore1.get("REDE_IP")).endswith(":"):
        variablestochangecore1['REDE_IP'] = variablestochangecore1['REDE_IP'][:-1]

    while str(variablestochangecore1.get("NETMASK")).endswith(":"):
        variablestochangecore1['NETMASK'] = variablestochangecore1['NETMASK'][:-1]

    len_ip_ipv6 = len(str(variablestochangecore1.get("REDE_IP")).split(':'))
    len_mask = len(str(variablestochangecore1.get("NETMASK")).split(':'))

    while(8-len_ip_ipv6>0):#8-6=2--8-7=1--8-8=0
        len_ip_ipv6 = len_ip_ipv6 + 1
        variablestochangecore1['REDE_IP'] = variablestochangecore1.get("REDE_IP")+":0"

    while(8-len_mask>0):
        len_mask = len_mask + 1
        variablestochangecore1['NETMASK'] = variablestochangecore1.get("NETMASK")+":0"

    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(variablestochangecore1.get("REDE_IP")).split(':')
    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(variablestochangecore1.get("NETMASK")).split(':')

    destroy_cache_function([vlan.id])
    network_ip.save()
 
    return network_ip
Пример #21
0
    def test_add_network_given_invalid_vip_environment_id(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))

        response = self.client.post("/network/ipv4/add/",
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env='a',
                                               net_type=1),
                                    content_type="text/xml")

        xml_map = self.parse_response(response)
        self.assertEquals(
            "Parameter id_ambiente_vip is invalid. Value: a",
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
Пример #22
0
    def test_add_network_given_vip_environment_not_found(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))
        self.mock_get_vip_environment_by_pk(EnvironmentVipNotFoundError(''))

        response = self.client.post("/network/ipv4/add/",
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env=1,
                                               net_type=1),
                                    content_type="text/xml")

        xml_map = self.parse_response(response)
        self.assertEquals(
            "Environment VIP not registered",
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
Пример #23
0
    def test_add_network_given_vlan_not_found(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))
        self.mock_get_vip_environment_by_pk(EnvironmentVip(id=1))
        add_network_mock = self.mock_add_network_ipv4(VlanNotFoundError(''))

        response = self.client.post('/network/ipv4/add/',
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env=1,
                                               net_type=1),
                                    content_type='text/xml')

        xml_map = self.parse_response(response)
        self.assertEquals(
            'VLAN not registered',
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
        self.assertTrue(add_network_mock.called)
Пример #24
0
    def test_add_network_given_invalid_environment_config(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))
        self.mock_get_vip_environment_by_pk(EnvironmentVip(id=1))
        add_network_mock = self.mock_add_network_ipv4(
            ConfigEnvironmentInvalidError(''))

        response = self.client.post("/network/ipv4/add/",
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env=1,
                                               net_type=1),
                                    content_type="text/xml")

        xml_map = self.parse_response(response)
        self.assertEquals(
            "Invalid Environment Configuration or not registered",
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
        self.assertTrue(add_network_mock.called)
Пример #25
0
    def test_add_network_given_no_more_available_ip_addresses(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))
        self.mock_get_vip_environment_by_pk(EnvironmentVip(id=1))
        add_network_mock = self.mock_add_network_ipv4(
            NetworkIPv4AddressNotAvailableError(''))

        response = self.client.post("/network/ipv4/add/",
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env=1,
                                               net_type=1),
                                    content_type="text/xml")

        xml_map = self.parse_response(response)
        self.assertEquals(
            "Unavailable address to create a NetworkIPv4",
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
        self.assertTrue(add_network_mock.called)
Пример #26
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE request to remove network type

        URL: /net_type/<id_net_type>/

        """

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

            # Get URL args
            id_net_type = kwargs.get('id_net_type')

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

            net_type = TipoRede.get_by_pk(id_net_type)

            with distributedlock(LOCK_TYPE_NETWORK % id_net_type):

                # Check if network type is used by vlan
                if net_type.networkipv4_set.count(
                ) > 0 or net_type.networkipv6_set.count() > 0:
                    self.log.error(u'Network type used by network.')
                    raise NetTypeUsedByNetworkError(
                        None, u'Network type used by network.')

                try:
                    net_type.delete()
                except Exception, e:
                    self.log.error(u'Failed to remove network type.')
                    raise VlanError(e, u'Failed to remove network type.')

            # Return empty response
            return self.response(dumps_networkapi({}))
Пример #27
0
    def test_add_network_given_successfully(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))
        self.mock_get_vip_environment_by_pk(EnvironmentVip(id=1))
        add_network_mock = self.mock_add_network_ipv4(self.get_vlan_map())
        self.mock_get_equipamento_ambiente(
            EquipamentoAmbiente(equipamento=Equipamento(id=1)))
        self.mock_get_first_available_ip("192.168.10.18")
        self.mock_ip_save()
        self.mock_ip_equipamento_create()

        response = self.client.post("/network/ipv4/add/",
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env=1,
                                               net_type=1),
                                    content_type="text/xml")

        xml_map = self.parse_response(response)
        self.assertIsNotNone(xml_map.get('networkapi').get('vlan'))
        self.assertEquals(200, response.status_code)
        self.assertTrue(add_network_mock.called)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE request to remove network type

        URL: /net_type/<id_net_type>/ 

        """

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

            # Get URL args
            id_net_type = kwargs.get('id_net_type')

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

            net_type = TipoRede.get_by_pk(id_net_type)

            with distributedlock(LOCK_TYPE_NETWORK % id_net_type):

                # Check if network type is used by vlan
                if net_type.networkipv4_set.count() > 0 or net_type.networkipv6_set.count() > 0:
                    self.log.error(u'Network type used by network.')
                    raise NetTypeUsedByNetworkError(
                        None, u'Network type used by network.')

                try:
                    net_type.delete(user)
                except Exception, e:
                    self.log.error(u'Failed to remove network type.')
                    raise VlanError(e, u'Failed to remove network type.')

            # Return empty response
            return self.response(dumps_networkapi({}))
Пример #29
0
    def test_add_network_given_no_first_ip_available(self):
        self.mock_get_network_type_by_pk(TipoRede(id=1))
        self.mock_get_vip_environment_by_pk(EnvironmentVip(id=1))
        add_network_mock = self.mock_add_network_ipv4({'vlan': {}})
        self.mock_get_equipamento_ambiente(
            EquipamentoAmbiente(equipamento=Equipamento(id=1)))
        self.mock_get_first_available_ip(
            IpNotAvailableError('Endereço IP não dispoínvel'))

        response = self.client.post("/network/ipv4/add/",
                                    XML.format(cidr='24',
                                               vlan=1,
                                               vip_env=1,
                                               net_type=1),
                                    content_type="text/xml")

        xml_map = self.parse_response(response)
        self.assertEquals(
            "Causa: Endereço IP não dispoínvel, Mensagem: None",
            xml_map.get('networkapi').get('erro').get('descricao'))
        self.assertEquals(500, response.status_code)
        self.assertTrue(add_network_mock.called)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Environment Configuration Prefix

        URL: environment/configuration/add
        """

        try:

            self._validate_permission(user)

            xml_map, _ = loads(request.raw_post_data)

            networkapi_map = xml_map.get('networkapi')

            self._validate_xml_networkapi(networkapi_map)

            network_map = networkapi_map.get('ambiente')

            self._validate_xml_network(network_map)

            # Get XML data
            network = network_map.get('network')
            id_environment = network_map.get('id_environment')
            ip_version = network_map.get('ip_version')
            network_type = network_map.get('network_type')
            prefix = network_map.get('prefix')

            self._validate_network(network, prefix)

            self._validate_environment_id(id_environment)

            self._validate_ip_version(ip_version)

            self._validate_network_type(network_type)

            self._validate_prefix_by_net_type(prefix, ip_version)

            environment = Ambiente().get_by_pk(id_environment)

            network_type = TipoRede.get_by_pk(network_type)

            ip_config = IPConfig()
            ip_config.subnet = network
            ip_config.new_prefix = prefix
            ip_config.type = ip_version
            ip_config.network_type = network_type

            ip_config.save()

            config_environment = ConfigEnvironment()
            config_environment.environment = environment
            config_environment.ip_config = ip_config

            config_environment.save()

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

        except PermissionError:
            return self.not_authorized()

        except AmbienteNotFoundError, e:
            return self.response_error(112)
    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)
Пример #32
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)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Network

        URL: network/add/
        """

        try:

            # Commons Validations

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

            # Business Validations

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

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

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

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

            # VLAN

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

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

            # Network Type

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

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

            # Environment Vip

            if environment_vip is not None:

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

                evips = EnvironmentVip.objects.all()

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

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

            else:
                env_vip = None

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

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

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

            # Business Rules

            if version == IP_VERSION.IPv4[0]:

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

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

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

                if env_vip is not None:

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

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

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

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

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

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

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

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

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

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

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

                # # Filter case 1 - end ##

                # New NetworkIPv4
                network_ip = NetworkIPv4()

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

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

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

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

                if env_vip is not None:

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

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

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

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

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

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

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

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

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

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

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

                # # Filter case 1 - end ##

                # New NetworkIPv6
                network_ip = NetworkIPv6()

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

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

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

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

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

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

            expl.append(str(net.prefixlen))

            ids_exclude = []
            ids_all = []

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

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

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

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

            # Set Vlan
            network_ip.vlan = vlan

            # Set Network Type
            network_ip.network_type = net_type

            # Set Environment VIP
            network_ip.ambient_vip = env_vip

            # Persist
            try:

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

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

                if list_equip_routers_ambient:

                    if version == IP_VERSION.IPv4[0]:

                        if network_ip.block < 31:

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

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

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

                            ip_model.save(user)

                            for equip in list_equip_routers_ambient:

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

                    else:
                        if network_ip.block < 127:

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

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

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

                            ipv6_model.save(user)

                            for equip in list_equip_routers_ambient:

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

            except Exception, e:
                raise IpError(e, u'Error persisting Network.')
    def 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)
Пример #35
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to edit network types.

        URL: /net_type/<id_net_type>/

        """

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

            # Get URL args
            id_net_type = kwargs.get('id_net_type')

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

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

            # Get networkapi tag map
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no networkapi tag from request XML.')

            # Get net_type tag map
            net_type_map = networkapi_map.get('net_type')
            if net_type_map is None:
                return self.response_error(3, u'There is no net_type tag from request XML.')

            # Valid name attribute
            name = net_type_map.get('name')
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100):
                self.log.error(
                    u'Parameter %s is invalid. Value: %s.', 'name', name)
                raise InvalidValueError(None, 'name', name)

            net_type = TipoRede.get_by_pk(id_net_type)

            with distributedlock(LOCK_TYPE_NETWORK % id_net_type):

                try:
                    if name.lower() != net_type.tipo_rede.lower():
                        TipoRede.get_by_name(name)
                        raise NetworkTypeNameDuplicatedError(
                            None, u'Network type with name %s already exists' % name)
                except NetworkTypeNotFoundError:
                    pass

                net_type.tipo_rede = name
                try:
                    net_type.save()
                except Exception, e:
                    self.log.error(u'Failed to edit network type.')
                    raise VlanError(e, u'Failed to edit network type.')

            # Return empty response
            return self.response(dumps_networkapi({}))
Пример #36
0
    def handle_post(self, request, user, *args, **kwargs):
        """
        Handles POST requests to allocate a new VLAN.

        URL: vlan/
        """

        self.log.info('Allocate new VLAN')

        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)
            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 = vlan_map.get('id_ambiente')
            network_type = vlan_map.get('id_tipo_rede')
            name = vlan_map.get('nome')
            description = vlan_map.get('descricao')
            environment_vip = vlan_map.get('id_ambiente_vip')
            vrf = vlan_map.get('vrf')

            # Name must NOT be none and 50 is the maxsize
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 50):
                self.log.error(u'Parameter nome is invalid. Value: %s.', name)
                raise InvalidValueError(None, 'nome', name)

            # Description can NOT be greater than 200
            if not is_valid_string_minsize(description, 3, False) or not is_valid_string_maxsize(description, 200, False):
                self.log.error(
                    u'Parameter descricao is invalid. Value: %s.', description)
                raise InvalidValueError(None, 'descricao', description)

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

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

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

            # 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

            # 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 = TipoRede.get_by_pk(network_type)

            # Business Rules

            # New Vlan
            vlan = Vlan()
            vlan.nome = name
            vlan.descricao = description
            vlan.ambiente = env

            # Check if environment has min/max num_vlan value or use the value
            # thas was configured in settings
            if (vlan.ambiente.min_num_vlan_1 and vlan.ambiente.max_num_vlan_1) or (vlan.ambiente.min_num_vlan_2 and vlan.ambiente.max_num_vlan_2):
                min_num_01 = vlan.ambiente.min_num_vlan_1 if vlan.ambiente.min_num_vlan_1 and vlan.ambiente.max_num_vlan_1 else vlan.ambiente.min_num_vlan_2
                max_num_01 = vlan.ambiente.max_num_vlan_1 if vlan.ambiente.min_num_vlan_1 and vlan.ambiente.max_num_vlan_1 else vlan.ambiente.max_num_vlan_2
                min_num_02 = vlan.ambiente.min_num_vlan_2 if vlan.ambiente.min_num_vlan_2 and vlan.ambiente.max_num_vlan_2 else vlan.ambiente.min_num_vlan_1
                max_num_02 = vlan.ambiente.max_num_vlan_2 if vlan.ambiente.min_num_vlan_2 and vlan.ambiente.max_num_vlan_2 else vlan.ambiente.max_num_vlan_1
            else:
                min_num_01 = settings.MIN_VLAN_NUMBER_01
                max_num_01 = settings.MAX_VLAN_NUMBER_01
                min_num_02 = settings.MIN_VLAN_NUMBER_02
                max_num_02 = settings.MAX_VLAN_NUMBER_02

            # Persist
            vlan.create_new(user,
                            min_num_01,
                            max_num_01,
                            min_num_02,
                            max_num_02
                            )

            # New NetworkIPv4
            network_ipv4 = NetworkIPv4()
            vlan_map = network_ipv4.add_network_ipv4(user, vlan.id, net, evip)

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to edit an Network.

        URL: network/edit/
        '''

        self.log.info('Edit an Network')

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

            # Get XML data
            id_network = net_map.get('id_network')
            ip_type = net_map.get('ip_type')
            id_net_type = net_map.get('id_net_type')
            id_env_vip = net_map.get('id_env_vip')

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

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

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

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

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

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

            # Business Rules

            if (id_env_vip is not None):
                id_env_vip = EnvironmentVip.get_by_pk(id_env_vip)
            id_net_type = TipoRede.get_by_pk(id_net_type)

            # New network_tyoe

            # EDIT NETWORK IP4
            if int(ip_type) == 0:
                net = NetworkIPv4.get_by_pk(id_network)

                with distributedlock(LOCK_NETWORK_IPV4 % id_network):

                    if id_env_vip is not None:

                        if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id:

                            network = IPNetwork(
                                '%d.%d.%d.%d/%d' % (net.oct1, net.oct2, net.oct3, net.oct4, net.block))

                            # Find all networks related to environment vip
                            nets = NetworkIPv4.objects.select_related().filter(
                                ambient_vip__id=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 ip
                            # range as related the environment vip
                            if network in networks:
                                raise NetworkIpAddressNotAvailableError(
                                    None, u'Unavailable address to create a NetworkIPv4.')

                    net.edit_network_ipv4(user, id_net_type, id_env_vip)

            # EDIT NETWORK IP6
            else:
                net = NetworkIPv6.get_by_pk(id_network)

                with distributedlock(LOCK_NETWORK_IPV6 % id_network):

                    if id_env_vip is not None:

                        if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id:

                            network = IPNetwork('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (
                                net.block1, net.block2, net.block3, net.block4, net.block5, net.block6, net.block7, net.block8, net.block))

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

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

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

                    net.edit_network_ipv6(user, id_net_type, id_env_vip)

            # Delete vlan's cache
            # destroy_cache_function()

            return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def network_ipv6_add(self, user, vlan_id, network_type, environment_vip, prefix=None):

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

            # Network Type

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

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

            # Environment Vip

            if environment_vip is not None:

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

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

            else:
                evip = None

            # Business Rules

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

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

            if list_equip_routers_ambient:

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

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

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

                ipv6_model.save()

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

                for equip in list_equip_routers_ambient:

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

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

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

        except XMLError, e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Environment Configuration Prefix

        URL: environment/configuration/add
        """

        try:

            self._validate_permission(user)

            xml_map, _ = loads(request.raw_post_data)

            networkapi_map = xml_map.get('networkapi')

            self._validate_xml_networkapi(networkapi_map)

            network_map = networkapi_map.get('ambiente')

            self._validate_xml_network(network_map)

            # Get XML data
            network = network_map.get('network')
            id_environment = network_map.get('id_environment')
            ip_version = network_map.get('ip_version')
            network_type = network_map.get('network_type')
            prefix = network_map.get('prefix')

            self._validate_network(network, prefix)

            self._validate_environment_id(id_environment)

            self._validate_ip_version(ip_version)

            self._validate_network_type(network_type)

            self._validate_prefix_by_net_type(prefix, ip_version)

            # environment = Ambiente().get_by_pk(id_environment)

            network_type = TipoRede.get_by_pk(network_type)

            # ip_config = IPConfig()
            # ip_config.subnet = network
            # ip_config.new_prefix = prefix
            # ip_config.type = ip_version
            # ip_config.network_type = network_type
            #
            # ip_config.save()
            #
            # config_environment = ConfigEnvironment()
            # config_environment.environment = environment
            # config_environment.ip_config = ip_config
            #
            # config_environment.save()

            # save on cidr table
            logging.debug(
                "EnvironmentConfigurationAddResource - save on cidr table")
            data = dict()
            data['type'] = ip_version
            data['new_prefix'] = prefix
            data['network_type'] = network_type.id
            data['environment'] = id_environment
            data['subnet'] = network

            env = Ambiente()
            env.create_cidr(configs=[data])

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

        except PermissionError:
            return self.not_authorized()

        except AmbienteNotFoundError, e:
            return self.response_error(112)
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to edit network types.

        URL: /net_type/<id_net_type>/ 

        """

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

            # Get URL args
            id_net_type = kwargs.get('id_net_type')

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

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

            # Get networkapi tag map
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no networkapi tag from request XML.')

            # Get net_type tag map
            net_type_map = networkapi_map.get('net_type')
            if net_type_map is None:
                return self.response_error(3, u'There is no net_type tag from request XML.')

            # Valid name attribute
            name = net_type_map.get('name')
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100):
                self.log.error(
                    u'Parameter %s is invalid. Value: %s.', 'name', name)
                raise InvalidValueError(None, 'name', name)

            net_type = TipoRede.get_by_pk(id_net_type)

            with distributedlock(LOCK_TYPE_NETWORK % id_net_type):

                try:
                    if name.lower() != net_type.tipo_rede.lower():
                        TipoRede.get_by_name(name)
                        raise NetworkTypeNameDuplicatedError(
                            None, u'Network type with name %s already exists' % name)
                except NetworkTypeNotFoundError:
                    pass

                net_type.tipo_rede = name
                try:
                    net_type.save(user)
                except Exception, e:
                    self.log.error(u'Failed to edit network type.')
                    raise VlanError(e, u'Failed to edit network type.')

            # Return empty response
            return self.response(dumps_networkapi({}))
    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.')
    def network_ipv6_add(self, user, vlan_id, network_type, environment_vip, prefix=None):

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

            # Network Type

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

            # Environment Vip

            if environment_vip is not None:

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

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

            else:
                evip = None

            # Business Rules

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

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

            if list_equip_routers_ambient:

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

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

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

                ipv6_model.save()

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

                if vlan_map.get('vlan').get('vxlan'):
                    logging.debug('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(vlan_map['vlan']['id_network'], 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 = vlan_map['vlan']['id_network']
                        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(vlan_map['vlan']['id_network'], True)
                            router_ip = str(router_ip).split(':')
                            ipv6_model2 = Ipv6()
                            ipv6_model2.block1 = router_ip[0]
                            ipv6_model2.block2 = router_ip[1]
                            ipv6_model2.block3 = router_ip[2]
                            ipv6_model2.block4 = router_ip[3]
                            ipv6_model2.block5 = router_ip[4]
                            ipv6_model2.block6 = router_ip[5]
                            ipv6_model2.block7 = router_ip[6]
                            ipv6_model2.block8 = router_ip[7]
                            ipv6_model2.networkipv6_id = vlan_map['vlan']['id_network']
                            ipv6_model2.save(user)
                            Ipv6Equipament().create(user,
                                                    ipv6_model2.id,
                                                    equip.equipamento.id)

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

        except XMLError, e:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, e)
    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)
Пример #44
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to edit an Network.

        URL: network/edit/
        """

        self.log.info('Edit an Network')

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

            # Get XML data
            id_network = net_map.get('id_network')
            ip_type = net_map.get('ip_type')
            id_net_type = net_map.get('id_net_type')
            id_env_vip = net_map.get('id_env_vip')
            cluster_unit = net_map.get('cluster_unit')

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

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

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

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

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

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

            # Business Rules

            if (id_env_vip is not None):
                id_env_vip = EnvironmentVip.get_by_pk(id_env_vip)
            id_net_type = TipoRede.get_by_pk(id_net_type)

            # New network_tyoe

            # EDIT NETWORK IP4
            if int(ip_type) == 0:
                net = NetworkIPv4.get_by_pk(id_network)

                with distributedlock(LOCK_NETWORK_IPV4 % id_network):

                    if id_env_vip is not None:

                        if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id:

                            network = IPNetwork(
                                '%d.%d.%d.%d/%d' % (net.oct1, net.oct2, net.oct3, net.oct4, net.block))

                            # Find all networks related to environment vip
                            nets = NetworkIPv4.objects.filter(
                                ambient_vip__id=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 ip
                            # range as related the environment vip
                            if network in networks:
                                raise NetworkIpAddressNotAvailableError(
                                    None, u'Unavailable address to create a NetworkIPv4.')

                    net.edit_network_ipv4(
                        user, id_net_type, id_env_vip, cluster_unit)

            # EDIT NETWORK IP6
            else:
                net = NetworkIPv6.get_by_pk(id_network)

                with distributedlock(LOCK_NETWORK_IPV6 % id_network):

                    if id_env_vip is not None:

                        if net.ambient_vip is None or net.ambient_vip.id != id_env_vip.id:

                            network = IPNetwork('%s:%s:%s:%s:%s:%s:%s:%s/%d' % (
                                net.block1, net.block2, net.block3, net.block4, net.block5, net.block6, net.block7, net.block8, net.block))

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

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

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

                    net.edit_network_ipv6(user, id_net_type, id_env_vip)

            # Delete vlan's cache
            # destroy_cache_function()

            return self.response(dumps_networkapi({}))

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