Пример #1
0
def criar_vlan(user, variablestochangecore1, ambientes, active=1):

    # get environment
    ambiente = Ambiente()
    divisaodc = DivisaoDc()
    divisaodc = divisaodc.get_by_name(ambientes.get('DC'))
    ambiente_log = AmbienteLogico()
    ambiente_log = ambiente_log.get_by_name(ambientes.get('LOG'))
    ambiente = ambiente.search(divisaodc.id, ambiente_log.id)
    for amb in ambiente:
        if amb.grupo_l3.nome == ambientes.get('L3'):
            id_ambiente = amb
    # set vlan
    vlan = Vlan()
    vlan.acl_file_name = None
    vlan.acl_file_name_v6 = None
    vlan.num_vlan = variablestochangecore1.get('VLAN_NUM')
    vlan.nome = variablestochangecore1.get('VLAN_NAME')
    vlan.descricao = ''
    vlan.ambiente = id_ambiente
    vlan.ativada = active
    vlan.acl_valida = 0
    vlan.acl_valida_v6 = 0

    vlan.insert_vlan(user)

    return vlan
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()
def criar_vlan(user, variablestochangecore1, ambientes, active=1):

    #get environment
    ambiente = Ambiente()
    divisaodc = DivisaoDc()
    divisaodc = divisaodc.get_by_name(ambientes.get('DC'))
    ambiente_log = AmbienteLogico()
    ambiente_log = ambiente_log.get_by_name(ambientes.get('LOG'))
    ambiente = ambiente.search(divisaodc.id, ambiente_log.id)
    for  amb in ambiente:
        if amb.grupo_l3.nome==ambientes.get('L3'):
            id_ambiente = amb
    # set vlan
    vlan = Vlan()
    vlan.acl_file_name = None
    vlan.acl_file_name_v6 = None
    vlan.num_vlan = variablestochangecore1.get("VLAN_NUM")
    vlan.nome = variablestochangecore1.get("VLAN_NAME")
    vlan.descricao = ""
    vlan.ambiente = id_ambiente
    vlan.ativada = active
    vlan.acl_valida = 0
    vlan.acl_valida_v6 = 0

    vlan.insert_vlan(user)

    return vlan
Пример #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 create_logic_environment(env):
    """Create environment."""

    try:
        env_obj = AmbienteLogico()
        env_obj.create_v3(env)
    except EnvironmentErrorV3, e:
        raise ValidationAPIException(str(e))
    def test_task_id_create_in_put_deploy_one_server_pool_success(self, *args):
        """Test success of id task generate for server pool put deploy success."""

        mock_get_user = args[1]
        mock_get_pool = args[2]
        mock_update_real_pool = args[3]

        user = Usuario(id=1, nome='test')

        divisaodc = DivisaoDc(id=1, nome='test')
        amblog = AmbienteLogico(id=1, nome='test')
        gl3 = GrupoL3(id=1, nome='test')
        ambiente = Ambiente(id=1,
                            grupo_l3=gl3,
                            divisao_dc=divisaodc,
                            ambiente_logico=amblog)

        pool = ServerPool(id=1, identifier='test', environment=ambiente)

        mock_update_real_pool.return_value = pool
        mock_get_pool.return_value = pool
        mock_get_user.return_value = user

        redeploy({'id': pool.id}, user.id)

        mock_update_real_pool.assert_called_with([{'id': pool.id}], user)
Пример #8
0
    def test_task_id_create_in_delete_deploy_one_server_pool_success(
            self, *args):
        """Test success of id task generate for server pool delete deploy success."""

        mock_get_user = args[1]
        mock_get_pool = args[2]
        mock_delete_real_pool = args[3]

        user = Usuario(id=1, nome='test')

        divisaodc = DivisaoDc(id=1, nome='test')
        amblog = AmbienteLogico(id=1, nome='test')
        gl3 = GrupoL3(id=1, nome='test')
        ambiente = Ambiente(id=1,
                            grupo_l3=gl3,
                            divisao_dc=divisaodc,
                            ambiente_logico=amblog)

        optionpool = OptionPool(id=1, type='test', name='test')
        healthcheck = Healthcheck(id=1)
        pool = ServerPool(id=1,
                          identifier='test',
                          environment=ambiente,
                          servicedownaction=optionpool,
                          healthcheck=healthcheck)

        pool_serializer = serializers.PoolV3Serializer(pool)

        mock_delete_real_pool.return_value = pool
        mock_get_pool.return_value = pool
        mock_get_user.return_value = user

        undeploy(pool.id, user.id)

        mock_delete_real_pool.assert_called_with([pool_serializer.data], user)
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições de GET para consulta de ambientes.

        Permite a consulta de todos os ambientes, ambientes filtrados por divisao_dc,
        ambientes filtrados por divisão_dc e por ambiente_logico

        URLs: /ambiente/,
              /ambiente/divisao_dc/<id_divisao_dc>/,
              /ambiente/divisao_dc/<id_divisao_dc>/ambiente_logico/<id_amb_logico>/,
        """
        try:
            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            environment_list = []

            division_id = kwargs.get('id_divisao_dc')
            environment_logical_id = kwargs.get('id_amb_logico')

            if division_id is not None:
                if not is_valid_int_greater_zero_param(division_id):
                    self.log.error(
                        u'The division_id parameter is not a valid value: %s.',
                        division_id)
                    raise InvalidValueError(None, 'division_id', division_id)
                else:
                    division_dc = DivisaoDc.get_by_pk(division_id)

            if environment_logical_id is not None:
                if not is_valid_int_greater_zero_param(environment_logical_id):
                    self.log.error(
                        u'The environment_logical_id parameter is not a valid value: %s.',
                        environment_logical_id)
                    raise InvalidValueError(None, 'environment_logical_id',
                                            environment_logical_id)
                else:
                    loc_env = AmbienteLogico.get_by_pk(environment_logical_id)

            environments = Ambiente().search(
                division_id,
                environment_logical_id).select_related('grupo_l3',
                                                       'ambiente_logico',
                                                       'divisao_dc', 'filter')
            for environment in environments:
                environment_list.append(get_environment_map(environment))

            return self.response(
                dumps_networkapi({'ambiente': environment_list}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to remove Logical Environment.

        URL: logicalenvironment/<id_logicalenvironment>/
        """
        try:

            self.log.info("Remove Logical Environment")

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

            id_logicalenvironment = kwargs.get('id_logicalenvironment')

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

            # Find Logical Environment by ID to check if it exist
            loc_env = AmbienteLogico.get_by_pk(id_logicalenvironment)

            with distributedlock(LOCK_LOGICAL_ENVIRONMENT %
                                 id_logicalenvironment):

                try:

                    if loc_env.ambiente_set.count() > 0:
                        raise AmbienteLogicoUsedByEnvironmentError(
                            None,
                            u"O Ambiente Lógico %s tem ambiente associado." %
                            loc_env.id)

                    # remove Logical Environment
                    loc_env.delete()

                except AmbienteLogicoUsedByEnvironmentError, e:
                    raise e
                except Exception, e:
                    self.log.error(
                        u'Failed to remove the Logical Environment.')
                    raise AmbienteError(
                        e, u'Failed to remove the Logical Environment.')
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Logical Environment.

        URL: logicalenvironment/
        """

        try:

            self.log.info('Add Logical Environment')

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

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

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

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

            # Get XML data
            name = logical_environment_map.get('name')

            try:
                AmbienteLogico.get_by_name(name)
                raise AmbienteLogicoNameDuplicatedError(
                    None, u'Já existe um Ambiente Lógico com o valor name %s.' % name)
            except AmbienteLogicoNotFoundError:
                pass

            log_env = AmbienteLogico()

            # set variables
            log_env.nome = name

            try:
                # save Logical Environment
                log_env.save()
            except Exception, e:
                self.log.error(u'Failed to save the Logical Environment.')
                raise AmbienteError(
                    e, u'Failed to save the Logical Environment.')

            log_env_map = dict()
            log_env_map['logical_environment'] = model_to_dict(
                log_env, exclude=['nome'])

            return self.response(dumps_networkapi(log_env_map))
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to remove Logical Environment.

        URL: logicalenvironment/<id_logicalenvironment>/
        """
        try:

            self.log.info("Remove Logical Environment")

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

            id_logicalenvironment = kwargs.get('id_logicalenvironment')

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

            # Find Logical Environment by ID to check if it exist
            loc_env = AmbienteLogico.get_by_pk(id_logicalenvironment)

            with distributedlock(LOCK_LOGICAL_ENVIRONMENT % id_logicalenvironment):

                try:

                    if loc_env.ambiente_set.count() > 0:
                        raise AmbienteLogicoUsedByEnvironmentError(
                            None, u"O Ambiente Lógico %s tem ambiente associado." % loc_env.id)

                    # remove Logical Environment
                    loc_env.delete(user)

                except AmbienteLogicoUsedByEnvironmentError, e:
                    raise e
                except Exception, e:
                    self.log.error(
                        u'Failed to remove the Logical Environment.')
                    raise AmbienteError(
                        e, u'Failed to remove the Logical Environment.')
Пример #13
0
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições de GET para consulta de ambientes.

        Permite a consulta de todos os ambientes, ambientes filtrados por divisao_dc,
        ambientes filtrados por divisão_dc e por ambiente_logico

        URLs: /ambiente/,
              /ambiente/divisao_dc/<id_divisao_dc>/,
              /ambiente/divisao_dc/<id_divisao_dc>/ambiente_logico/<id_amb_logico>/,
        """
        try:
            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
                return self.not_authorized()

            environment_list = []

            division_id = kwargs.get('id_divisao_dc')
            environment_logical_id = kwargs.get('id_amb_logico')

            if division_id is not None:
                if not is_valid_int_greater_zero_param(division_id):
                    self.log.error(
                        u'The division_id parameter is not a valid value: %s.', division_id)
                    raise InvalidValueError(None, 'division_id', division_id)
                else:
                    division_dc = DivisaoDc.get_by_pk(division_id)

            if environment_logical_id is not None:
                if not is_valid_int_greater_zero_param(environment_logical_id):
                    self.log.error(
                        u'The environment_logical_id parameter is not a valid value: %s.', environment_logical_id)
                    raise InvalidValueError(
                        None, 'environment_logical_id', environment_logical_id)
                else:
                    loc_env = AmbienteLogico.get_by_pk(environment_logical_id)

            environments = Ambiente().search(
                division_id, environment_logical_id).select_related('grupo_l3', 'ambiente_logico', 'divisao_dc', 'filter')
            for environment in environments:
                environment_list.append(get_environment_map(environment))

            return self.response(dumps_networkapi({'ambiente': environment_list}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Пример #14
0
def criar_ambiente(user,
                   ambientes,
                   ranges,
                   acl_path=None,
                   filter=None,
                   vrf=None):

    # ambiente cloud
    environment = Ambiente()
    environment.grupo_l3 = GrupoL3()
    environment.ambiente_logico = AmbienteLogico()
    environment.divisao_dc = DivisaoDc()

    environment.grupo_l3.id = environment.grupo_l3.get_by_name(
        ambientes.get('L3')).id
    environment.ambiente_logico.id = environment.ambiente_logico.get_by_name(
        ambientes.get('LOG')).id
    environment.divisao_dc.id = environment.divisao_dc.get_by_name(
        ambientes.get('DC')).id

    environment.acl_path = acl_path
    environment.ipv4_template = None
    environment.ipv6_template = None
    if vrf is not None:
        environment.vrf = vrf

    environment.max_num_vlan_1 = ranges.get('MAX')
    environment.min_num_vlan_1 = ranges.get('MIN')
    environment.max_num_vlan_2 = ranges.get('MAX')
    environment.min_num_vlan_2 = ranges.get('MIN')

    environment.link = ' '

    if filter is not None:
        try:
            filter_obj = Filter.objects.get(name__iexact=filter)
            environment.filter = filter_obj
        except ObjectDoesNotExist:
            pass

    environment.create(user)

    return environment
 def create_environment(self):
     return Ambiente(divisao_dc=DivisaoDc(nome='division_1'), ambiente_logico=AmbienteLogico(nome='env'), grupo_l3=GrupoL3(nome='l3'))
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit Logical Environment.

        URL: logicalenvironment/<id_logicalenvironment>/
        """
        try:

            self.log.info("Edit Logical Environment")

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

            id_logicalenvironment = kwargs.get('id_logicalenvironment')

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

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

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

            # Get XML data
            name = logical_environment_map.get('name')

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

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

            # Find Logical Environment by ID to check if it exist
            loc_env = AmbienteLogico.get_by_pk(id_logicalenvironment)

            with distributedlock(LOCK_LOGICAL_ENVIRONMENT %
                                 id_logicalenvironment):

                try:
                    if loc_env.nome.lower() != name.lower():
                        AmbienteLogico.get_by_name(name)
                        raise AmbienteLogicoNameDuplicatedError(
                            None,
                            u'Já existe um Ambiente Lógico com o valor name %s.'
                            % name)
                except AmbienteLogicoNotFoundError:
                    pass

                # set variables
                loc_env.nome = name

                try:
                    # update Logical Environment
                    loc_env.save()
                except Exception, e:
                    self.log.error(
                        u'Failed to update the Logical Environment.')
                    raise AmbienteError(
                        e, u'Failed to update the Logical Environment.')

                return self.response(dumps_networkapi({}))

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

        URL: logicalenvironment/
        """

        try:

            self.log.info("Add Logical Environment")

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

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

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

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

            # Get XML data
            name = logical_environment_map.get('name')

            try:
                AmbienteLogico.get_by_name(name)
                raise AmbienteLogicoNameDuplicatedError(
                    None,
                    u'Já existe um Ambiente Lógico com o valor name %s.' %
                    name)
            except AmbienteLogicoNotFoundError:
                pass

            log_env = AmbienteLogico()

            # set variables
            log_env.nome = name

            try:
                # save Logical Environment
                log_env.save()
            except Exception, e:
                self.log.error(u'Failed to save the Logical Environment.')
                raise AmbienteError(
                    e, u'Failed to save the Logical Environment.')

            log_env_map = dict()
            log_env_map['logical_environment'] = model_to_dict(
                log_env, exclude=["nome"])

            return self.response(dumps_networkapi(log_env_map))
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit Logical Environment.

        URL: logicalenvironment/<id_logicalenvironment>/
        """
        try:

            self.log.info("Edit Logical Environment")

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

            id_logicalenvironment = kwargs.get('id_logicalenvironment')

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

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

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

            # Get XML data
            name = logical_environment_map.get('name')

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

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

            # Find Logical Environment by ID to check if it exist
            loc_env = AmbienteLogico.get_by_pk(id_logicalenvironment)

            with distributedlock(LOCK_LOGICAL_ENVIRONMENT % id_logicalenvironment):

                try:
                    if loc_env.nome.lower() != name.lower():
                        AmbienteLogico.get_by_name(name)
                        raise AmbienteLogicoNameDuplicatedError(
                            None, u'Já existe um Ambiente Lógico com o valor name %s.' % name)
                except AmbienteLogicoNotFoundError:
                    pass

                # set variables
                loc_env.nome = name

                try:
                    # update Logical Environment
                    loc_env.save(user)
                except Exception, e:
                    self.log.error(
                        u'Failed to update the Logical Environment.')
                    raise AmbienteError(
                        e, u'Failed to update the Logical Environment.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Пример #19
0
    def handle_put(self, request, user, *args, **kwargs):
        """Trata requisições PUT para alterar um Ambiente.

        URL: ambiente/<id_ambiente>/
        """

        try:

            environment_id = kwargs.get('id_ambiente')
            if not is_valid_int_greater_zero_param(environment_id):
                self.log.error(
                    u'The environment_id parameter is not a valid value: %s.', environment_id)
                raise InvalidValueError(None, 'environment_id', environment_id)

            if not has_perm(user,
                            AdminPermission.ENVIRONMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            xml_map, attrs_map = loads(request.raw_post_data)

            self.log.debug('XML_MAP: %s', xml_map)

            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.')

            environment_map = networkapi_map.get('ambiente')
            if environment_map is None:
                return self.response_error(3, u'Não existe valor para a tag ambiente do XML de requisição.')

            l3_group_id = environment_map.get('id_grupo_l3')
            if not is_valid_int_greater_zero_param(l3_group_id):
                self.log.error(
                    u'The l3_group_id parameter is not a valid value: %s.', l3_group_id)
                raise InvalidValueError(None, 'l3_group_id', l3_group_id)
            else:
                l3_group_id = int(l3_group_id)

            GrupoL3.get_by_pk(l3_group_id)

            logic_environment_id = environment_map.get('id_ambiente_logico')
            if not is_valid_int_greater_zero_param(logic_environment_id):
                self.log.error(
                    u'The logic_environment_id parameter is not a valid value: %s.', logic_environment_id)
                raise InvalidValueError(
                    None, 'logic_environment_id', logic_environment_id)
            else:
                logic_environment_id = int(logic_environment_id)

            AmbienteLogico.get_by_pk(logic_environment_id)

            dc_division_id = environment_map.get('id_divisao')
            if not is_valid_int_greater_zero_param(dc_division_id):
                self.log.error(
                    u'The dc_division_id parameter is not a valid value: %s.', dc_division_id)
                raise InvalidValueError(None, 'dc_division_id', dc_division_id)
            else:
                dc_division_id = int(dc_division_id)

            DivisaoDc.get_by_pk(dc_division_id)

            link = environment_map.get('link')
            if not is_valid_string_maxsize(link, 200, False):
                self.log.error(u'Parameter link is invalid. Value: %s', link)
                raise InvalidValueError(None, 'link', link)

            vrf = environment_map.get('vrf')
            if not is_valid_string_maxsize(link, 100, False):
                self.log.error(u'Parameter vrf is invalid. Value: %s', vrf)
                raise InvalidValueError(None, 'vrf', vrf)

            filter_id = environment_map.get('id_filter')
            if filter_id is not None:
                if not is_valid_int_greater_zero_param(filter_id):
                    self.log.error(
                        u'Parameter filter_id is invalid. Value: %s.', filter_id)
                    raise InvalidValueError(None, 'filter_id', filter_id)

                filter_id = int(filter_id)
                # Filter must exist
                Filter.get_by_pk(filter_id)

            acl_path = environment_map.get('acl_path')
            if not is_valid_string_maxsize(acl_path, 250, False):
                self.log.error(
                    u'Parameter acl_path is invalid. Value: %s', acl_path)
                raise InvalidValueError(None, 'acl_path', acl_path)

            ipv4_template = environment_map.get('ipv4_template')
            if not is_valid_string_maxsize(ipv4_template, 250, False):
                self.log.error(
                    u'Parameter ipv4_template is invalid. Value: %s', ipv4_template)
                raise InvalidValueError(None, 'ipv4_template', ipv4_template)

            ipv6_template = environment_map.get('ipv6_template')
            if not is_valid_string_maxsize(ipv6_template, 250, False):
                self.log.error(
                    u'Parameter ipv6_template is invalid. Value: %s', ipv6_template)
                raise InvalidValueError(None, 'ipv6_template', ipv6_template)

            max_num_vlan_1 = environment_map.get('max_num_vlan_1')
            min_num_vlan_1 = environment_map.get('min_num_vlan_1')
            max_num_vlan_2 = environment_map.get('max_num_vlan_2')
            min_num_vlan_2 = environment_map.get('min_num_vlan_2')
            # validate  max_num_vlan_1 and min_num_vlan_1
            if (max_num_vlan_1 is not None and min_num_vlan_1 is None) or (min_num_vlan_1 is not None and max_num_vlan_1 is None):
                self.log.error(
                    u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
                raise InvalidValueError(
                    None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)

            if max_num_vlan_1 is not None and min_num_vlan_1 is not None:
                max_num_vlan_1 = int(max_num_vlan_1)
                min_num_vlan_1 = int(min_num_vlan_1)

                if max_num_vlan_1 < 1 or min_num_vlan_1 < 1:
                    self.log.error(
                        u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
                    raise InvalidValueError(
                        None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)
                if max_num_vlan_1 <= min_num_vlan_1:
                    self.log.error(
                        u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s', (min_num_vlan_1, max_num_vlan_1))
                    raise InvalidValueError(
                        None, 'min_num_vlan_1, max_num_vlan_1', min_num_vlan_1 + ',' + max_num_vlan_1)
            else:
                max_num_vlan_1 = max_num_vlan_2
                min_num_vlan_1 = min_num_vlan_2
            # validate  max_num_vlan_1 and min_num_vlan_1

            # validate  max_num_vlan_2 and min_num_vlan_2
            if (max_num_vlan_2 is not None and min_num_vlan_2 is None) or (min_num_vlan_2 is not None and max_num_vlan_2 is None):
                self.log.error(
                    u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
                raise InvalidValueError(
                    None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)

            if max_num_vlan_2 is not None and min_num_vlan_2 is not None:
                max_num_vlan_2 = int(max_num_vlan_2)
                min_num_vlan_2 = int(min_num_vlan_2)

                max_num_vlan_1 = int(max_num_vlan_1)
                min_num_vlan_1 = int(min_num_vlan_1)

                if max_num_vlan_2 < 1 or min_num_vlan_2 < 1:
                    self.log.error(
                        u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
                    raise InvalidValueError(
                        None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)

                if max_num_vlan_2 <= min_num_vlan_2:
                    self.log.error(
                        u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s', (min_num_vlan_2, max_num_vlan_2))
                    raise InvalidValueError(
                        None, 'min_num_vlan_2, max_num_vlan_2', min_num_vlan_2 + ',' + max_num_vlan_1)
            else:
                max_num_vlan_2 = max_num_vlan_1
                min_num_vlan_2 = min_num_vlan_1
            # validate  max_num_vlan_2 and min_num_vlan_2

            with distributedlock(LOCK_ENVIRONMENT % environment_id):

                # Delete vlan's cache
                key_list_db = Vlan.objects.filter(ambiente__pk=environment_id)
                key_list = []
                for key in key_list_db:
                    key_list.append(key.id)

                destroy_cache_function(key_list)

                # Destroy equipment's cache
                equip_id_list = []
                envr = Ambiente.get_by_pk(environment_id)
                for equipment in envr.equipamentoambiente_set.all():
                    equip_id_list.append(equipment.equipamento_id)

                destroy_cache_function(equip_id_list, True)

                Ambiente.update(user,
                                environment_id,
                                grupo_l3_id=l3_group_id,
                                ambiente_logico_id=logic_environment_id,
                                divisao_dc_id=dc_division_id,
                                filter_id=filter_id,
                                link=link,
                                vrf=vrf,
                                acl_path=fix_acl_path(acl_path),
                                ipv4_template=ipv4_template,
                                ipv6_template=ipv6_template,
                                max_num_vlan_1=max_num_vlan_1,
                                min_num_vlan_1=min_num_vlan_1,
                                max_num_vlan_2=max_num_vlan_2,
                                min_num_vlan_2=min_num_vlan_2)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_put(self, request, user, *args, **kwargs):
        """Trata requisições PUT para alterar um Ambiente.

        URL: ambiente/<id_ambiente>/
        """

        try:

            environment_id = kwargs.get('id_ambiente')
            if not is_valid_int_greater_zero_param(environment_id):
                self.log.error(
                    u'The environment_id parameter is not a valid value: %s.',
                    environment_id)
                raise InvalidValueError(None, 'environment_id', environment_id)

            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            xml_map, attrs_map = loads(request.raw_post_data)

            self.log.debug('XML_MAP: %s', xml_map)

            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.'
                )

            environment_map = networkapi_map.get('ambiente')
            if environment_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag ambiente do XML de requisição.'
                )

            l3_group_id = environment_map.get('id_grupo_l3')
            if not is_valid_int_greater_zero_param(l3_group_id):
                self.log.error(
                    u'The l3_group_id parameter is not a valid value: %s.',
                    l3_group_id)
                raise InvalidValueError(None, 'l3_group_id', l3_group_id)
            else:
                l3_group_id = int(l3_group_id)

            GrupoL3.get_by_pk(l3_group_id)

            logic_environment_id = environment_map.get('id_ambiente_logico')
            if not is_valid_int_greater_zero_param(logic_environment_id):
                self.log.error(
                    u'The logic_environment_id parameter is not a valid value: %s.',
                    logic_environment_id)
                raise InvalidValueError(None, 'logic_environment_id',
                                        logic_environment_id)
            else:
                logic_environment_id = int(logic_environment_id)

            AmbienteLogico.get_by_pk(logic_environment_id)

            dc_division_id = environment_map.get('id_divisao')
            if not is_valid_int_greater_zero_param(dc_division_id):
                self.log.error(
                    u'The dc_division_id parameter is not a valid value: %s.',
                    dc_division_id)
                raise InvalidValueError(None, 'dc_division_id', dc_division_id)
            else:
                dc_division_id = int(dc_division_id)

            DivisaoDc.get_by_pk(dc_division_id)

            link = environment_map.get('link')
            if not is_valid_string_maxsize(link, 200, False):
                self.log.error(u'Parameter link is invalid. Value: %s', link)
                raise InvalidValueError(None, 'link', link)

            vrf = environment_map.get('vrf')
            if not is_valid_string_maxsize(link, 100, False):
                self.log.error(u'Parameter vrf is invalid. Value: %s', vrf)
                raise InvalidValueError(None, 'vrf', vrf)

            filter_id = environment_map.get('id_filter')
            if filter_id is not None:
                if not is_valid_int_greater_zero_param(filter_id):
                    self.log.error(
                        u'Parameter filter_id is invalid. Value: %s.',
                        filter_id)
                    raise InvalidValueError(None, 'filter_id', filter_id)

                filter_id = int(filter_id)
                # Filter must exist
                Filter.get_by_pk(filter_id)

            acl_path = environment_map.get('acl_path')
            if not is_valid_string_maxsize(acl_path, 250, False):
                self.log.error(u'Parameter acl_path is invalid. Value: %s',
                               acl_path)
                raise InvalidValueError(None, 'acl_path', acl_path)

            ipv4_template = environment_map.get('ipv4_template')
            if not is_valid_string_maxsize(ipv4_template, 250, False):
                self.log.error(
                    u'Parameter ipv4_template is invalid. Value: %s',
                    ipv4_template)
                raise InvalidValueError(None, 'ipv4_template', ipv4_template)

            ipv6_template = environment_map.get('ipv6_template')
            if not is_valid_string_maxsize(ipv6_template, 250, False):
                self.log.error(
                    u'Parameter ipv6_template is invalid. Value: %s',
                    ipv6_template)
                raise InvalidValueError(None, 'ipv6_template', ipv6_template)

            max_num_vlan_1 = environment_map.get('max_num_vlan_1')
            min_num_vlan_1 = environment_map.get('min_num_vlan_1')
            max_num_vlan_2 = environment_map.get('max_num_vlan_2')
            min_num_vlan_2 = environment_map.get('min_num_vlan_2')
            # validate  max_num_vlan_1 and min_num_vlan_1
            if (max_num_vlan_1 is not None and min_num_vlan_1 is None) or (
                    min_num_vlan_1 is not None and max_num_vlan_1 is None):
                self.log.error(
                    u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s',
                    (min_num_vlan_1, max_num_vlan_1))
                raise InvalidValueError(None, 'min_num_vlan_1, max_num_vlan_1',
                                        min_num_vlan_1 + ',' + max_num_vlan_1)

            if max_num_vlan_1 is not None and min_num_vlan_1 is not None:
                max_num_vlan_1 = int(max_num_vlan_1)
                min_num_vlan_1 = int(min_num_vlan_1)

                if max_num_vlan_1 < 1 or min_num_vlan_1 < 1:
                    self.log.error(
                        u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s',
                        (min_num_vlan_1, max_num_vlan_1))
                    raise InvalidValueError(
                        None, 'min_num_vlan_1, max_num_vlan_1',
                        min_num_vlan_1 + ',' + max_num_vlan_1)
                if max_num_vlan_1 <= min_num_vlan_1:
                    self.log.error(
                        u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s',
                        (min_num_vlan_1, max_num_vlan_1))
                    raise InvalidValueError(
                        None, 'min_num_vlan_1, max_num_vlan_1',
                        min_num_vlan_1 + ',' + max_num_vlan_1)
            else:
                max_num_vlan_1 = max_num_vlan_2
                min_num_vlan_1 = min_num_vlan_2
            # validate  max_num_vlan_1 and min_num_vlan_1

            # validate  max_num_vlan_2 and min_num_vlan_2
            if (max_num_vlan_2 is not None and min_num_vlan_2 is None) or (
                    min_num_vlan_2 is not None and max_num_vlan_2 is None):
                self.log.error(
                    u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s',
                    (min_num_vlan_2, max_num_vlan_2))
                raise InvalidValueError(None, 'min_num_vlan_2, max_num_vlan_2',
                                        min_num_vlan_2 + ',' + max_num_vlan_1)

            if max_num_vlan_2 is not None and min_num_vlan_2 is not None:
                max_num_vlan_2 = int(max_num_vlan_2)
                min_num_vlan_2 = int(min_num_vlan_2)

                max_num_vlan_1 = int(max_num_vlan_1)
                min_num_vlan_1 = int(min_num_vlan_1)

                if max_num_vlan_2 < 1 or min_num_vlan_2 < 1:
                    self.log.error(
                        u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s',
                        (min_num_vlan_2, max_num_vlan_2))
                    raise InvalidValueError(
                        None, 'min_num_vlan_2, max_num_vlan_2',
                        min_num_vlan_2 + ',' + max_num_vlan_1)

                if max_num_vlan_2 <= min_num_vlan_2:
                    self.log.error(
                        u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s',
                        (min_num_vlan_2, max_num_vlan_2))
                    raise InvalidValueError(
                        None, 'min_num_vlan_2, max_num_vlan_2',
                        min_num_vlan_2 + ',' + max_num_vlan_1)
            else:
                max_num_vlan_2 = max_num_vlan_1
                min_num_vlan_2 = min_num_vlan_1
            # validate  max_num_vlan_2 and min_num_vlan_2

            with distributedlock(LOCK_ENVIRONMENT % environment_id):

                # Delete vlan's cache
                key_list_db = Vlan.objects.filter(ambiente__pk=environment_id)
                key_list = []
                for key in key_list_db:
                    key_list.append(key.id)

                destroy_cache_function(key_list)

                # Destroy equipment's cache
                equip_id_list = []
                envr = Ambiente.get_by_pk(environment_id)
                for equipment in envr.equipamentoambiente_set.all():
                    equip_id_list.append(equipment.equipamento_id)

                destroy_cache_function(equip_id_list, True)

                Ambiente.update(user,
                                environment_id,
                                grupo_l3_id=l3_group_id,
                                ambiente_logico_id=logic_environment_id,
                                divisao_dc_id=dc_division_id,
                                filter_id=filter_id,
                                link=link,
                                vrf=vrf,
                                acl_path=fix_acl_path(acl_path),
                                ipv4_template=ipv4_template,
                                ipv6_template=ipv6_template,
                                max_num_vlan_1=max_num_vlan_1,
                                min_num_vlan_1=min_num_vlan_1,
                                max_num_vlan_2=max_num_vlan_2,
                                min_num_vlan_2=min_num_vlan_2)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Trata requisições POST para inserir novo Ambiente.

        URL: ambiente/ or ambiente/ipconfig/
        """

        try:

            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            xml_map, attrs_map = loads(request.raw_post_data)

            self.log.debug('XML_MAP: %s', xml_map)

            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.'
                )

            environment_map = networkapi_map.get('ambiente')
            if environment_map is None:
                return self.response_error(
                    3,
                    u'Não existe valor para a tag ambiente do XML de requisição.'
                )

            link = environment_map.get('link')
            if not is_valid_string_maxsize(link, 200, False):
                self.log.error(u'Parameter link is invalid. Value: %s', link)
                raise InvalidValueError(None, 'link', link)

            l3_group_id = environment_map.get('id_grupo_l3')
            if not is_valid_int_greater_zero_param(l3_group_id):
                self.log.error(
                    u'The l3_group_id parameter is not a valid value: %s.',
                    l3_group_id)
                raise InvalidValueError(None, 'l3_group_id', l3_group_id)
            else:
                l3_group_id = int(l3_group_id)

            logic_environment_id = environment_map.get('id_ambiente_logico')
            if not is_valid_int_greater_zero_param(logic_environment_id):
                self.log.error(
                    u'The logic_environment_id parameter is not a valid value: %s.',
                    logic_environment_id)
                raise InvalidValueError(None, 'logic_environment_id',
                                        logic_environment_id)
            else:
                logic_environment_id = int(logic_environment_id)

            dc_division_id = environment_map.get('id_divisao')
            if not is_valid_int_greater_zero_param(dc_division_id):
                self.log.error(
                    u'The dc_division_id parameter is not a valid value: %s.',
                    dc_division_id)
                raise InvalidValueError(None, 'dc_division_id', dc_division_id)
            else:
                dc_division_id = int(dc_division_id)

            filter_id = environment_map.get('id_filter')
            if filter_id is not None:
                if not is_valid_int_greater_zero_param(filter_id):
                    self.log.error(
                        u'Parameter filter_id is invalid. Value: %s.',
                        filter_id)
                    raise InvalidValueError(None, 'filter_id', filter_id)

            acl_path = environment_map.get('acl_path')
            if not is_valid_string_maxsize(acl_path, 250, False):
                self.log.error(u'Parameter acl_path is invalid. Value: %s',
                               acl_path)
                raise InvalidValueError(None, 'acl_path', acl_path)

            ipv4_template = environment_map.get('ipv4_template')
            if not is_valid_string_maxsize(ipv4_template, 250, False):
                self.log.error(
                    u'Parameter ipv4_template is invalid. Value: %s',
                    ipv4_template)
                raise InvalidValueError(None, 'ipv4_template', ipv4_template)

            ipv6_template = environment_map.get('ipv6_template')
            if not is_valid_string_maxsize(ipv6_template, 250, False):
                self.log.error(
                    u'Parameter ipv6_template is invalid. Value: %s',
                    ipv6_template)
                raise InvalidValueError(None, 'ipv6_template', ipv6_template)

            max_num_vlan_1 = environment_map.get('max_num_vlan_1')
            min_num_vlan_1 = environment_map.get('min_num_vlan_1')
            max_num_vlan_2 = environment_map.get('max_num_vlan_2')
            min_num_vlan_2 = environment_map.get('min_num_vlan_2')
            # validate  max_num_vlan_1 and min_num_vlan_1
            if (max_num_vlan_1 is not None and min_num_vlan_1 is None) or (
                    min_num_vlan_1 is not None and max_num_vlan_1 is None):
                self.log.error(
                    u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s',
                    (min_num_vlan_1, max_num_vlan_1))
                raise InvalidValueError(None, 'min_num_vlan_1, max_num_vlan_1',
                                        min_num_vlan_1 + ',' + max_num_vlan_1)

            if max_num_vlan_1 is not None and min_num_vlan_1 is not None:
                max_num_vlan_1 = int(max_num_vlan_1)
                min_num_vlan_1 = int(min_num_vlan_1)

                if max_num_vlan_1 < 1 or min_num_vlan_1 < 1:
                    self.log.error(
                        u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s',
                        (min_num_vlan_1, max_num_vlan_1))
                    raise InvalidValueError(
                        None, 'min_num_vlan_1, max_num_vlan_1',
                        min_num_vlan_1 + ',' + max_num_vlan_1)
                if max_num_vlan_1 <= min_num_vlan_1:
                    self.log.error(
                        u'Parameters min_num_vlan_1, max_num_vlan_1  is invalid. Values: %s, %s',
                        (min_num_vlan_1, max_num_vlan_1))
                    raise InvalidValueError(
                        None, 'min_num_vlan_1, max_num_vlan_1',
                        min_num_vlan_1 + ',' + max_num_vlan_1)
            else:
                max_num_vlan_1 = max_num_vlan_2
                min_num_vlan_1 = min_num_vlan_2
            # validate  max_num_vlan_1 and min_num_vlan_1

            # validate  max_num_vlan_2 and min_num_vlan_2
            if (max_num_vlan_2 is not None and min_num_vlan_2 is None) or (
                    min_num_vlan_2 is not None and max_num_vlan_2 is None):
                self.log.error(
                    u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s',
                    (min_num_vlan_2, max_num_vlan_2))
                raise InvalidValueError(None, 'min_num_vlan_2, max_num_vlan_2',
                                        min_num_vlan_2 + ',' + max_num_vlan_1)

            if max_num_vlan_2 is not None and min_num_vlan_2 is not None:
                max_num_vlan_2 = int(max_num_vlan_2)
                min_num_vlan_2 = int(min_num_vlan_2)

                max_num_vlan_1 = int(max_num_vlan_1)
                min_num_vlan_1 = int(min_num_vlan_1)

                if max_num_vlan_2 < 1 or min_num_vlan_2 < 1:
                    self.log.error(
                        u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s',
                        (min_num_vlan_2, max_num_vlan_2))
                    raise InvalidValueError(
                        None, 'min_num_vlan_2, max_num_vlan_2',
                        min_num_vlan_2 + ',' + max_num_vlan_1)

                if max_num_vlan_2 <= min_num_vlan_2:
                    self.log.error(
                        u'Parameters min_num_vlan_2, max_num_vlan_2  is invalid. Values: %s, %s',
                        (min_num_vlan_2, max_num_vlan_2))
                    raise InvalidValueError(
                        None, 'min_num_vlan_2, max_num_vlan_2',
                        min_num_vlan_2 + ',' + max_num_vlan_1)
            else:
                max_num_vlan_2 = max_num_vlan_1
                min_num_vlan_2 = min_num_vlan_1
            # validate  max_num_vlan_2 and min_num_vlan_2

            vrf = environment_map.get('vrf')
            if not is_valid_string_maxsize(vrf, 100, False):
                self.log.error(u'Parameter vrf is invalid. Value: %s', vrf)
                raise InvalidValueError(None, 'link', vrf)

            environment = Ambiente()
            environment.grupo_l3 = GrupoL3()
            environment.ambiente_logico = AmbienteLogico()
            environment.divisao_dc = DivisaoDc()
            environment.grupo_l3.id = l3_group_id
            environment.ambiente_logico.id = logic_environment_id
            environment.divisao_dc.id = dc_division_id
            environment.acl_path = fix_acl_path(acl_path)
            environment.ipv4_template = ipv4_template
            environment.ipv6_template = ipv6_template
            environment.max_num_vlan_1 = max_num_vlan_1
            environment.min_num_vlan_1 = min_num_vlan_1
            environment.max_num_vlan_2 = max_num_vlan_2
            environment.min_num_vlan_2 = min_num_vlan_2
            environment.vrf = vrf

            if filter_id is not None:
                environment.filter = Filter()
                environment.filter.id = filter_id

            environment.link = link

            environment.create(user)

            # IP Config
            ip_config = kwargs.get('ip_config')

            # If ip config is set
            if ip_config:

                # Add this to environment
                id_ip_config = environment_map.get('id_ip_config')

                # Valid ip config
                if not is_valid_int_greater_zero_param(id_ip_config):
                    raise InvalidValueError(None, 'id_ip_config', id_ip_config)

                # Ip config must exists
                ip_conf = IPConfig().get_by_pk(id_ip_config)

                # Makes the relationship
                config = ConfigEnvironment()
                config.environment = environment
                config.ip_config = ip_conf

                config.save()

            environment_map = dict()
            environment_map['id'] = environment.id

            return self.response(
                dumps_networkapi({'ambiente': environment_map}))

        except GrupoError:
            return self.response_error(1)

        except XMLError, x:
            self.log.error(u'Erro ao ler o XML da requisicao.')
            return self.response_error(3, x)