def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to find all Racks

        URLs: /rack/list-rack-environment/<rack_id>/
        """

        self.log.info('Find all racks environment')

        try:

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

            environment_list = []
            id = kwargs.get('rack_id')
            env = EnvironmentRack()
            environments = env.get_by_rack(id)
            for envs in environments:
                envs = model_to_dict(envs)
                amb = Ambiente()
                ambiente = amb.get_by_pk(envs['ambiente'])
                if "PROD" in ambiente.ambiente_logico.nome:
                    environment_list.append(get_environment_map(ambiente))

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

        except UserNotAuthorizedError:
            return self.not_authorized()

        except RackError:
            return self.response_error(397)
Beispiel #2
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 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
Beispiel #4
0
def update_environment(env):
    """
    Update environment

    :param env: dict
    """

    env_obj = get_environment_by_id(env.get('id'))

    Ambiente.update(
        None,
        env_obj.id,
        grupo_l3_id=env.get('grupo_l3'),
        ambiente_logico_id=env.get('ambiente_logico'),
        divisao_dc_id=env.get('divisao_dc'),
        filter_id=env.get('filter'),
        acl_path=env.get('acl_path'),
        ipv4_template=env.get('ipv4_template'),
        ipv6_template=env.get('ipv6_template'),
        link=env.get('link'),
        min_num_vlan_1=env.get('min_num_vlan_1'),
        max_num_vlan_1=env.get('max_num_vlan_1'),
        min_num_vlan_2=env.get('min_num_vlan_2'),
        max_num_vlan_2=env.get('max_num_vlan_2'),
        vrf=env.get('vrf'),
        default_vrf=env.get('default_vrf'),
        father_environment_id=env.get('father_environment'),
    )

    # configs of environment
    # env_id = env.get('id')
    # configs = env.get('configs', [])
    # ips_by_env = IPConfig.get_by_environment(None, env_id)
    # ids_conf_current = [ip_by_env.id for ip_by_env in ips_by_env]

    # if configs:
    #     # configs with ids
    #     ids_conf_receive = [cfg.get('id') for cfg in configs
    #                         if cfg.get('id')]

    #     # configs to update: configs with id
    #     cfg_upt = [cfg for cfg in configs if cfg.get('id') and
    #                cfg.get('id') in ids_conf_current]

    #     # configs to create: configs without id
    #     cfg_ins = [cfg for cfg in configs if not cfg.get('id')]

    #     # configs to delete: configs not received
    #     cfg_del = [id_conf for id_conf in ids_conf_current
    #                if id_conf not in ids_conf_receive]

    #     update_configs(cfg_upt, env_id)
    #     create_configs(cfg_ins, env_id)
    #     delete_configs(cfg_del, env_id)

    # else:
    #     delete_configs(ids_conf_current, env_id)

    return env_obj
Beispiel #5
0
def create_environment(env):
    """Create environment."""

    try:
        env_obj = Ambiente()
        env_obj.create_v3(env)
    except EnvironmentErrorV3, e:
        raise ValidationAPIException(str(e))
Beispiel #6
0
def create_environment(env):
    """Create environment."""

    try:
        env_obj = Ambiente()
        env_obj.create_v3(env)
    except EnvironmentErrorV3, e:
        raise ValidationAPIException(str(e))
Beispiel #7
0
def delete_environment(env_ids):
    """
    Delete environment

    :param env: dict
    """

    for env_id in env_ids:
        Ambiente.remove(None, env_id)
Beispiel #8
0
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to verify that the IP belongs to environment.

        URLs:  /ip/x1.x2.x3.x4/ambiente/<id_amb>
        URLs:  /ip/<ip>/ambiente/<id_amb>
        """

        self.log.info("GET to verify that the IP belongs to environment")

        try:

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

            environment_id = kwargs.get('id_amb')

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

            ip = kwargs.get('ip')

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

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

            # Existing IP
            octs = str(IPAddress(ip, 4).exploded).split('.')
            ip = Ip.get_by_octs_and_environment(octs[0], octs[1], octs[2],
                                                octs[3], environment_id)

            # Build dictionary return
            ip_map = dict()
            ip_map['id'] = ip.id
            ip_map['id_vlan'] = ip.networkipv4.vlan.id
            ip_map['oct4'] = ip.oct4
            ip_map['oct3'] = ip.oct3
            ip_map['oct2'] = ip.oct2
            ip_map['oct1'] = ip.oct1
            ip_map['descricao'] = ip.descricao

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

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to verify that the IP belongs to environment.

        URLs:  /ip/x1.x2.x3.x4/ambiente/<id_amb>
        URLs:  /ip/<ip>/ambiente/<id_amb>
        """

        self.log.info("GET to verify that the IP belongs to environment")

        try:

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

            environment_id = kwargs.get('id_amb')

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

            ip = kwargs.get('ip')

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

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

            # Existing IP
            octs = str(IPAddress(ip, 4).exploded).split('.')
            ip = Ip.get_by_octs_and_environment(
                octs[0], octs[1], octs[2], octs[3], environment_id)

            # Build dictionary return
            ip_map = dict()
            ip_map['id'] = ip.id
            ip_map['id_vlan'] = ip.networkipv4.vlan.id
            ip_map['oct4'] = ip.oct4
            ip_map['oct3'] = ip.oct3
            ip_map['oct2'] = ip.oct2
            ip_map['oct1'] = ip.oct1
            ip_map['descricao'] = ip.descricao

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

        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 Rack.

        URL: interface/associar-ambiente/
        """
        try:
            self.log.info('Associa interface aos ambientes')

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_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.'
                )

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

            # Get XML data
            env = interface_map.get('ambiente')
            interface = interface_map.get('interface')

            amb_int = EnvironmentInterface()
            interfaces = Interface()
            amb = Ambiente()

            amb_int.interface = interfaces.get_by_pk(int(interface))
            amb_int.ambiente = amb.get_by_pk(int(env))

            amb_int.create(user)

            amb_int_map = dict()
            amb_int_map['interface_ambiente'] = amb_int

            return self.response(dumps_networkapi(amb_int_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Beispiel #11
0
def create_environment(env):
    """Create environment."""

    try:
        env_obj = Ambiente()
        env_obj.create_v3(env)
    except EnvironmentErrorV3 as e:
        raise ValidationAPIException(str(e))
    except ValidationAPIException as e:
        raise ValidationAPIException(str(e))
    except Exception as e:
        raise NetworkAPIException(str(e))

    return env_obj
    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)
Beispiel #13
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)
Beispiel #14
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()
Beispiel #15
0
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests GET to Remove Prefix Configuration.

        URL: /environment/configuration/remove/environment_id/configuration_id/
        """
        try:

            configuration_id = kwargs.get('configuration_id')

            environment_id = kwargs.get('environment_id')

            self._validate_permission(user)

            self._validate_configuration_id(configuration_id)

            self._validate_environment_id(environment_id)

            ip_config = IPConfig.remove(self, user, environment_id,
                                        configuration_id)

            # remove from cidr table
            logging.debug("Remove config from cidr table.")
            Ambiente().delete_cidr([configuration_id])

            return self.response(dumps_networkapi({'ip_config': ip_config}))

        except PermissionError:
            return self.not_authorized()

        except IPConfigNotFoundError, e:
            self.log.error(u'IpCofig not registred')
            return self.response_error(301)
 def create_server_pool_model(self):
     return ServerPool(
         id=1,
         default_port=8080,
         identifier='pool_1',
         environment=Ambiente(id=1)
     )
    def create(self, authenticated_user):
        '''Insert a new associoation between rack and environment

        @return: Nothing

        @raise AmbienteNotFoundError: Ambiente does not exists.

        @raise EnvironmentRackDuplicatedError: Rack already related to environment

        @raise EnvironmentRackError: Not able to complete.
        '''

        self.ambiente = Ambiente().get_by_pk(self.ambiente.id)
        self.rack = Rack().get_by_pk(self.rack.id)

        try:
            exist = EnvironmentRack().get_by_rack_environment(
                self.rack.id, self.ambiente.id)
            raise EnvironmentRackDuplicatedError(
                None, u'EnvironmentRack already registered for rack and environment.')
        except EnvironmentRackNotFoundError:
            pass

        try:
            self.save()
        except Exception, e:
            self.log.error(u'Error trying to insert EnvironmentRack: %s/%s.' %
                           (self.rack.id, self.ambiente.id))
            raise EnvironmentRackError(
                e, u'Error trying to insert EnvironmentRack: %s/%s.' % (self.rack.id, self.ambiente.id))
Beispiel #18
0
    def _create_ifaces_on_trunks(self, sw_router, envs_vlans):

        interface_list = EnvironmentInterface.objects.all().filter(
            interface=sw_router.id)

        for int_env in interface_list:
            int_env.delete()

        if type(envs_vlans) is not list:
            envs_vlans = [envs_vlans]

        for i in envs_vlans:

            environment = Ambiente.get_by_pk(int(i.get('env')))
            env_iface = EnvironmentInterface()
            env_iface.interface = sw_router
            env_iface.ambiente = environment

            range_vlans = i.get('vlans')
            if range_vlans:
                api_interface_facade.verificar_vlan_range(
                    environment, range_vlans)

                env_iface.vlans = range_vlans

            env_iface.create()
Beispiel #19
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handle GET requests to get Environment by id.

            URLs: /environment/id/<environment_id>/,
        """
        try:
            if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            environment_list = []

            environment_id = kwargs.get('environment_id')

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

            environment_list.append(
                get_environment_map(Ambiente().get_by_pk(environment_id)))

            return self.response(
                dumps_networkapi({'ambiente': environment_list}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
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 handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to save a new Rule

        URL: rule/save/
        """
        try:
            self.log.info("Save rule to an environment")

            # User permission
            if not has_perm(user, AdminPermission.VIP_VALIDATION, 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.')

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

            # Get XML data
            id_env = rule_map['id_env']
            name = rule_map['name']
            contents = rule_map['contents'] if type(
                rule_map['contents']) is list else [rule_map['contents'], ]
            blocks_id = rule_map['blocks_id'] if type(
                rule_map['blocks_id']) is list else [rule_map['blocks_id'], ]

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

            if not name or len(name) > 80:
                self.log.error(
                    u'The name parameter is not a valid value: %s.', name)
                raise InvalidValueError(None, 'name', name)

            environment = Ambiente.get_by_pk(id_env)

            new_rule = Rule()
            new_rule.name = name
            new_rule.environment = environment
            new_rule.save()

            self.__save_rule_contents(
                contents, blocks_id, environment, new_rule, user)

            return self.response(dumps_networkapi({}))

        except AmbienteNotFoundError, e:
            self.log.error('Environment not found')
            return self.response_error(112)
    def handle_delete(self, request, user, *args, **kwargs):
        """
        Handles DELETE requests to create a relationship of Environment with EnvironmentVip.

        URL: environment/<environment_id>/environmentvip/<environment_vip_id>/
        """

        self.log.info("Remove a relationship of Environment with EnvironmentVip")

        try:

            # Commons Validations

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

            # Valid Environment
            environment_id = kwargs.get("environment_id")
            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)

            # Valid EnvironmentVip ID
            environment_vip_id = kwargs.get("environment_vip_id")
            if not is_valid_int_greater_zero_param(environment_vip_id):
                self.log.error(u"The id_environment_vip parameter is not a valid value: %s.", environment_vip_id)
                raise InvalidValueError(None, "environment_vip_id", environment_vip_id)

            # Business Validations

            # Existing Environment ID
            environment = Ambiente.get_by_pk(environment_id)
            # Existing EnvironmentVip ID
            environment_vip = EnvironmentVip.get_by_pk(environment_vip_id)
            # Business Rules
            environment_environment_vip = EnvironmentEnvironmentVip().get_by_environment_environment_vip(
                environment.id, environment_vip.id
            )
            server_pool_list = EnvironmentEnvironmentVip.get_server_pool_member_by_environment_environment_vip(
                environment_environment_vip
            )

            # Valid integraty between environment/environmentvip related with reals
            # if exists reals fot this environment then raise a exception
            if server_pool_list:
                raise EnvironmentEnvironmentServerPoolLinked({"environment": environment.name})

            # Delete
            environment_environment_vip.delete()

            # Return nothing
            return self.response(dumps_networkapi({}))

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

        URL: rule/save/
        """
        try:
            self.log.info('Save rule to an environment')

            # User permission
            if not has_perm(user, AdminPermission.VIP_VALIDATION, 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.')

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

            # Get XML data
            id_env = rule_map['id_env']
            name = rule_map['name']
            contents = rule_map['contents'] if type(
                rule_map['contents']) is list else [rule_map['contents'], ]
            blocks_id = rule_map['blocks_id'] if type(
                rule_map['blocks_id']) is list else [rule_map['blocks_id'], ]

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

            if not name or len(name) > 80:
                self.log.error(
                    u'The name parameter is not a valid value: %s.', name)
                raise InvalidValueError(None, 'name', name)

            environment = Ambiente.get_by_pk(id_env)

            new_rule = Rule()
            new_rule.name = name
            new_rule.environment = environment
            new_rule.save()

            self.__save_rule_contents(
                contents, blocks_id, environment, new_rule, user)

            return self.response(dumps_networkapi({}))

        except AmbienteNotFoundError, e:
            self.log.error('Environment not found')
            return self.response_error(112)
Beispiel #24
0
def save_or_update(self, request, user, update=False):

    try:
        # User permission
        if not has_perm(user, AdminPermission.VIP_VALIDATION,
                        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.')

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

        environment_id = map['id_env']
        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)

        environment = Ambiente.get_by_pk(environment_id)

        if update:
            for block in environment.blockrules_set.all():
                block.delete()
        else:
            if environment.blockrules_set.count() > 0:
                return self.response_error(357)

        if 'blocks' in map:
            blocks = map['blocks'] if type(map['blocks']) is list else [
                map['blocks'],
            ]
            for order, content in enumerate(blocks):

                block = BlockRules()

                block.content = content
                block.order = order
                block.environment = environment

                block.save()

        return self.response(dumps_networkapi({}))

    except AmbienteNotFoundError, e:
        self.log.error('Environment not found')
        return self.response_error(112)
Beispiel #25
0
    def _validate_environment_id(self, id_environment):

        if not is_valid_int_greater_zero_param(id_environment):
            self.log.error(
                u'The id_environment parameter is invalid value: %s.', id_environment)
            raise InvalidValueError(None, 'id_environment', id_environment)

        Ambiente().get_by_pk(id_environment)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Rack.

        URL: interface/associar-ambiente/
        """
        try:
            self.log.info("Associa interface aos ambientes")

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_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.')

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

            # Get XML data
            env = interface_map.get('ambiente')
            interface = interface_map.get('interface')

            amb_int = EnvironmentInterface()
            interfaces = Interface()
            amb = Ambiente()

            amb_int.interface = interfaces.get_by_pk(int(interface))
            amb_int.ambiente = amb.get_by_pk(int(env))

            amb_int.create(user)

            amb_int_map = dict()
            amb_int_map['interface_ambiente'] = amb_int

            return self.response(dumps_networkapi(amb_int_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to list all Environments.

        URL: /ambiente/equip/id_equip
        """

        try:

            # Commons Validations

            # User permission

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

            id_equip = kwargs.get('id_equip')

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

            # Business Rules
            equip = Equipamento.get_by_pk(id_equip)
            environments_list = EquipamentoAmbiente.get_by_equipment(equip.id)

            # Get all environments in DB
            lists_aux = []
            for environment in environments_list:
                env = Ambiente.get_by_pk(environment.ambiente.id)
                env_map = model_to_dict(env)
                env_map['grupo_l3_name'] = env.grupo_l3.nome
                env_map['ambiente_logico_name'] = env.ambiente_logico.nome
                env_map['divisao_dc_name'] = env.divisao_dc.nome
                env_map['is_router'] = environment.is_router

                try:
                    env_map['range'] = str(
                        env.min_num_vlan_1) + ' - ' + str(env.max_num_vlan_1)
                    if env.min_num_vlan_1 != env.min_num_vlan_2:
                        env_map['range'] = env_map[
                            'range'] + '; ' + str(env.min_num_vlan_2) + ' - ' + str(env.max_num_vlan_2)
                except:
                    env_map['range'] = 'Nao definido'

                if env.filter is not None:
                    env_map['filter_name'] = env.filter.name

                lists_aux.append(env_map)
            # Return XML
            environment_list = dict()
            environment_list['ambiente'] = lists_aux
            return self.response(dumps_networkapi(environment_list))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
    def 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()
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata requisições DELETE para remover um Ambiente.

        URL: ambiente/<id_ambiente>/
        """

        try:

            environment_id = kwargs.get('id_ambiente')

            # Valid ID Environment
            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()

            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.remove(user, environment_id)

                return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_delete(self, request, user, *args, **kwargs):
        """Trata requisições DELETE para remover um Ambiente.

        URL: ambiente/<id_ambiente>/
        """

        try:

            environment_id = kwargs.get('id_ambiente')

            # Valid ID Environment
            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()

            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.remove(user, environment_id)

                return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Beispiel #31
0
def post_cidr(obj):

    from netaddr import IPNetwork

    try:
        cidr = EnvCIDR()

        data = dict()
        data['id'] = obj.get('id')
        data['ip_version'] = obj.get('ip_version')
        data['subnet_mask'] = obj.get('subnet_mask')
        data['network_type'] = obj.get('network_type')
        data['environment'] = obj.get('environment')
        data['network'] = obj.get('network')

        try:
            network = IPNetwork(obj.get('network'))
        except Exception as e:
            raise ValidationAPIException(str(e))

        environment = Ambiente().get_by_pk(int(obj.get('environment')))
        msg = list()
        if not cidr.check_cidr(environment, obj.get('network')):
            message = "The network is not a subnet of the father environment."
            msg.append(
                dict(message=message, environment_id=obj.get('environment')))
            log.info(message)

        duplicated_cidr = cidr.check_duplicated_cidr(environment,
                                                     obj.get('network'))

        duplicated_ids = [ids.id_env.id for ids in duplicated_cidr]

        if duplicated_cidr:
            message = "CIDR %s overlaps with networks from environments: %s" % \
                      (obj.get('network'), duplicated_ids)
            msg.append(
                dict(message=message, environment_id=obj.get('environment')))
            log.info(message)

        data['network_first_ip'] = int(network.ip)
        data['network_last_ip'] = int(network.broadcast)
        data['network_mask'] = network.prefixlen

        response = cidr.post(data)

    except CIDRErrorV3 as e:
        raise ValidationAPIException(str(e))
    except ValidationAPIException as e:
        raise ValidationAPIException(str(e))
    except Exception as e:
        raise NetworkAPIException(str(e))

    return response, msg
def save_or_update(self, request, user, update=False):

    try:
        # User permission
        if not has_perm(user, AdminPermission.VIP_VALIDATION, 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.')

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

        environment_id = map['id_env']
        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)

        environment = Ambiente.get_by_pk(environment_id)

        if update:
            for block in environment.blockrules_set.all():
                block.delete()
        else:
            if environment.blockrules_set.count() > 0:
                return self.response_error(357)

        if 'blocks' in map:
            blocks = map['blocks'] if type(
                map['blocks']) is list else [map['blocks'], ]
            for order, content in enumerate(blocks):

                block = BlockRules()

                block.content = content
                block.order = order
                block.environment = environment

                block.save()

        return self.response(dumps_networkapi({}))

    except AmbienteNotFoundError, e:
        self.log.error('Environment not found')
        return self.response_error(112)
Beispiel #33
0
def get_environment_by_id(environment_id):
    """Return a environment by id.

    Args:
        environment_id: Id of environment
    """

    try:
        environment = Ambiente.get_by_pk(id=environment_id)
    except AmbienteNotFoundError, e:
        raise exceptions.EnvironmentDoesNotExistException(str(e))
Beispiel #34
0
def get_environment_by_id(environment_id):
    """Return a environment by id.

    Args:
        environment_id: Id of environment
    """

    try:
        environment = Ambiente.get_by_pk(id=environment_id)
    except AmbienteNotFoundError, e:
        raise exceptions.EnvironmentDoesNotExistException(str(e))
Beispiel #35
0
    def _create_ifaces_on_trunks(self, iface, envs_vlans):
        log.debug("_create_ifaces_on_trunks")

        for i in envs_vlans:

            environment = Ambiente.get_by_pk(int(i.get('env')))
            env_iface = EnvironmentInterface()
            env_iface.interface = iface
            env_iface.ambiente = environment
            env_iface.vlans = i.get('vlans')
            env_iface.create()
    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)
Beispiel #37
0
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to find all Racks

        URLs: /rack/list-rack-environment/<rack_id>/
        """

        self.log.info('Find all racks environment')

        try:

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

            environment_list = []
            id = kwargs.get('rack_id')
            env = EnvironmentRack()
            environments = env.get_by_rack(id)
            for envs in environments:
                envs = model_to_dict(envs)
                amb = Ambiente()
                ambiente = amb.get_by_pk(envs['ambiente'])
                if "PROD" in ambiente.ambiente_logico.nome:
                    environment_list.append(get_environment_map(ambiente))

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

        except UserNotAuthorizedError:
            return self.not_authorized()

        except RackError:
            return self.response_error(397)
Beispiel #38
0
    def test_update_pool_fields(self):
        pool = ServerPool()
        default_port = 8080
        env = Ambiente(id=1)
        identifier = 'pool_1'
        old_healthcheck = Healthcheck()
        old_lb_method = 'round-robin'
        old_maxconn = 50

        save_pool_mock = self.mock_save_pool()
        update_pool_fields(default_port, env, identifier, old_healthcheck,
                           old_lb_method, old_maxconn, pool, self.user)

        save_pool_mock.assert_calls(call(), call())
        self.assertEquals(default_port, pool.default_port)
        self.assertEquals(env, pool.environment)
        self.assertEquals(identifier, pool.identifier)
        self.assertEquals(old_healthcheck, pool.healthcheck)
        self.assertEquals(old_lb_method, pool.lb_method)
    def handle_get(self, request, user, *args, **kwargs):
        """Trata as requisições GET para consulta de HealthCheckExpects.

        Lista as informações dos HealthCheckExpect's de um determinado ambiente.

        URL:  /healthcheckexpect/ambiente/<id_amb>/
        """
        try:
            if not has_perm(user, AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.READ_OPERATION):
                return self.not_authorized()

            map_list = []

            environment_id = kwargs.get('id_amb')
            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)

            environment = Ambiente().get_by_pk(environment_id)

            healthcheckexpects = HealthcheckExpect().search(environment_id)

            for healthcheckexpect in healthcheckexpects:
                healthcheckexpect_map = dict()
                healthcheckexpect_map['id'] = healthcheckexpect.id
                healthcheckexpect_map[
                    'expect_string'] = healthcheckexpect.expect_string
                healthcheckexpect_map[
                    'match_list'] = healthcheckexpect.match_list
                healthcheckexpect_map[
                    'id_ambiente'] = healthcheckexpect.ambiente_id

                map_list.append(healthcheckexpect_map)

            return self.response(
                dumps_networkapi({'healthcheck_expect': map_list}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def setUp(self):
        self.user = Usuario()
        self.equipment_list = [Equipamento(id=1, nome='router')]
        self.ambiente = Ambiente()
        self.vlan = Vlan(id=1, ambiente=self.ambiente)
        self.networkv4 = NetworkIPv4(id=1,
                                     vlan=self.vlan,
                                     oct1=192,
                                     oct2=168,
                                     oct3=0,
                                     oct4=0,
                                     mask_oct1=255,
                                     mask_oct2=255,
                                     mask_oct3=255,
                                     mask_oct4=0)

        self.networkv6 = NetworkIPv6(id=1,
                                     vlan=self.vlan,
                                     block1='fff',
                                     block2='fff',
                                     block3='fff',
                                     block4='fff',
                                     block5='fff',
                                     block6='fff',
                                     block7='fff',
                                     block8='fff',
                                     mask1='fff',
                                     mask2='fff',
                                     mask3='fff',
                                     mask4='fff',
                                     mask5='fff',
                                     mask6='fff',
                                     mask7='fff',
                                     mask8='fff')

        self.mock_distributed_lock()
        self.mock_transaction()
    def handle_delete(self, request, user, *args, **kwargs):
        """Treat Delete requests to remove related Equipment and  Environment

        URL: equipment/<id_equip>/environment/<id_amb>/
        """

        self.log.info('Remove EquipmentEnvironment by id')

        try:

            # Business Validations

            id_equipment = kwargs.get('id_equipment')
            id_environment = kwargs.get('id_environment')

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

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

            # Find Equipment by ID to check if it exist
            Equipamento.get_by_pk(id_equipment)

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

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

            with distributedlock(LOCK_EQUIPMENT_ENVIRONMENT % id_environment):
                '''
                equip_env = EquipamentoAmbiente().get_by_equipment_environment(
                    id_equipment, id_environment)

                is_error = False
                ipv4_error = ""
                ipv6_error = ""

                for ipequip in equip_env.equipamento.ipequipamento_set.all():

                    if ipequip.ip.networkipv4.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv4_error += " %s.%s.%s.%s - Vip %s ," % (
                                ip.oct1, ip.oct2, ip.oct3, ip.oct4, e.cause)

                for ipequip in equip_env.equipamento.ipv6equipament_set.all():

                    if ipequip.ip.networkipv6.vlan.ambiente.id == int(id_environment):
                        try:
                            ip = ipequip.ip
                            ipequip.remove(user, ip.id, ipequip.equipamento.id)
                        except IpCantBeRemovedFromVip, e:
                            is_error = True
                            ipv6_error += " %s:%s:%s:%s:%s:%s:%s:%s - Vip %s ," % (
                                ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8, e.cause)

                if is_error:
                    return self.response_error(336, environment.show_environment(), ipv4_error, ipv6_error)

                # Remove Equipment - Environment
                '''
                EquipamentoAmbiente.remove(user, id_equipment, id_environment)

                return self.response(dumps_networkapi({}))

        except EquipamentoNotFoundError, e:
            return self.response_error(117, id_equipment)
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to create new VLAN without add NetworkIPv4.

        URLs: /vlan/no-network/
        """

        self.log.info('Create new VLAN without add NetworkIPv4')

        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('environment_id')
            name = vlan_map.get('name')
            description = vlan_map.get('description')
            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 name is invalid. Value: %s.', name)
                raise InvalidValueError(None, 'name', 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 description is invalid. Value: %s.',
                               description)
                raise InvalidValueError(None, 'description', 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
            try:

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

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

            except AmbienteNotFoundError, e:
                self.log.error(u'The environment parameter does not exist.')
                return self.response_error(112)

            # 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

            #To avoid allocation same vlan number twice for different environments in same equipments
            #Lock all environments related to this environment when allocating vlan number
            #select all equipments from this environment that are not part of a filter
            # and them selects all environments from all these equipments and lock them out
            filtered_equipment_type_ids = list()

            env_filter = None
            try:
                env_filter = env.filter.id
            except:
                pass

            for fet in FilterEquipType.objects.filter(filter=env_filter):
                filtered_equipment_type_ids.append(fet.equiptype.id)

            filtered_environment_equips = Equipamento.objects.filter(
                equipamentoambiente__ambiente=env).exclude(
                    tipo_equipamento__in=filtered_equipment_type_ids)

            #select all environments from the equips that were not filtered
            locks_list = list()
            environments_list = Ambiente.objects.filter(
                equipamentoambiente__equipamento__in=filtered_environment_equips
            ).distinct().order_by('id')
            for environment in environments_list:
                lock = distributedlock(LOCK_ENVIRONMENT % environment.id)
                lock.__enter__()
                locks_list.append(lock)

            # Persist
            try:
                vlan.create_new(user, min_num_01, max_num_01, min_num_02,
                                max_num_02)
            except Exception, e:
                #release all the locks if failed
                for lock in locks_list:
                    lock.__exit__('', '', '')
                raise e
    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):
        """Treat requests POST to add Rack.

        URL: channel/inserir/
        """
        try:
            self.log.info("Inserir novo Channel")

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_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.')

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

            # Get XML data
            interfaces = channel_map.get('interfaces')
            nome = channel_map.get('nome')
            lacp = channel_map.get('lacp')
            int_type = channel_map.get('int_type')
            vlan = channel_map.get('vlan')
            envs = channel_map.get('envs')
            port_channel = PortChannel()
            interface = Interface()
            amb = Ambiente()

            cont = []

            port_channel.nome = str(nome)
            port_channel.lacp = convert_string_or_int_to_boolean(lacp)
            port_channel.create(user)

            interfaces = str(interfaces).split('-')

            int_type = TipoInterface.get_by_name(str(int_type))
            for var in interfaces:
                if not var=="" and not var==None:
                    interf = interface.get_by_pk(int(var))
                    try:
                        sw_router = interf.get_switch_and_router_interface_from_host_interface(interf.protegida)
                    except:
                        raise InterfaceError("Interface não conectada")

                    if sw_router.channel is not None:
                        raise InterfaceError("Interface %s já está em um Channel" % sw_router.interface)

                    for i in interface.search(sw_router.equipamento.id):
                        if i.channel is not None:
                            raise InterfaceError("Equipamento %s já possui um Channel" % sw_router.equipamento.nome)

                    if cont is []:
                        cont.append(int(sw_router.equipamento.id))
                    elif not sw_router.equipamento.id in cont:
                        cont.append(int(sw_router.equipamento.id))
                        if len(cont) > 2:
                            raise InterfaceError("Mais de dois equipamentos foram selecionados")

                    if sw_router.ligacao_front is not None:
                        ligacao_front_id = sw_router.ligacao_front.id
                    else:
                        ligacao_front_id = None
                    if sw_router.ligacao_back is not None:
                        ligacao_back_id = sw_router.ligacao_back.id
                    else:
                        ligacao_back_id = None

                    Interface.update(user,
                                     sw_router.id,
                                     interface=sw_router.interface,
                                     protegida=sw_router.protegida,
                                     descricao=sw_router.descricao,
                                     ligacao_front_id=ligacao_front_id,
                                     ligacao_back_id=ligacao_back_id,
                                     tipo=int_type,
                                     vlan_nativa=vlan,
                                     channel=port_channel)

                    if "trunk" in int_type.tipo:
                        interface_list = EnvironmentInterface.objects.all().filter(interface=sw_router.id)
                        for int_env in interface_list:
                            int_env.delete(user)
                        if envs is not None:
                            if not type(envs)==unicode:
                                for env in envs:
                                    amb_int = EnvironmentInterface()
                                    amb_int.interface = sw_router
                                    amb_int.ambiente = amb.get_by_pk(int(env))
                                    amb_int.create(user)
                            else:
                                amb_int = EnvironmentInterface()
                                amb_int.interface = sw_router
                                amb_int.ambiente = amb.get_by_pk(int(envs))
                                amb_int.create(user)

            port_channel_map = dict()
            port_channel_map['port_channel'] = port_channel

            return self.response(dumps_networkapi({'port_channel': port_channel_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 insert vlan

        URL: vlan/insert/
        '''

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

            # Commons Validations

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

            # Business Validations

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            vlan = Vlan()

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

                # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                vlan.get_vlan_by_acl(acl_file)

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

                # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                vlan.get_vlan_by_acl_v6(acl_file_v6)

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

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

            vlan.insert_vlan(user)

            if network_ipv4:
                NetworkIPv4().add_network_ipv4(user, vlan.id, None, None, None)

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

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

            # Delete vlan's cache
            # destroy_cache_function()

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

        except VlanACLDuplicatedError, e:
            return self.response_error(311, acl_file)
    def handle_put(self, request, user, *args, **kwargs):
        """Handles PUT requests to update a given Rule

        URL: rule/update/
        """
        try:
            self.log.info('Update rule to an environment')

            # User permission
            if not has_perm(user, AdminPermission.VIP_VALIDATION, 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.')

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

            # Get XML data
            id_rule = rule_map['id_rule']
            id_env = rule_map['id_env']
            name = rule_map['name']
            contents = rule_map['contents'] if type(
                rule_map['contents']) is list else [rule_map['contents'], ]
            blocks_id = rule_map['blocks_id'] if type(
                rule_map['blocks_id']) is list else [rule_map['blocks_id'], ]

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

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

            if not name or len(name) > 80:
                self.log.error(
                    u'The name parameter is not a valid value: %s.', name)
                raise InvalidValueError(None, 'name', name)

            rule = Rule.objects.get(pk=id_rule)

            environment = Ambiente.get_by_pk(id_env)

            rule.name = name
            rule.environment = environment

            # Set NULL in rule field of all Vip Request related
            RequisicaoVips.objects.filter(rule=rule).update(rule=None)
            RequisicaoVips.objects.filter(
                rule_applied=rule).update(rule_applied=None)
            RequisicaoVips.objects.filter(
                rule_rollback=rule).update(rule_rollback=None)

            rule.save()

            for rule_cotent in rule.rulecontent_set.all():
                rule_cotent.delete()

            self.__save_rule_contents(
                contents, blocks_id, environment, rule, user)

            return self.response(dumps_networkapi({}))

        except AmbienteNotFoundError, e:
            self.log.error('Environment not found')
            return self.response_error(112)
 def test_alter_valid(self):
     mock = self.mock_valid_alter()
     response = self.alter(self.ID_ALTER_VALID, {self.XML_KEY: mock})
     valid_response(response)
     environ = Ambiente.get_by_pk(self.ID_ALTER_VALID)
     self.valid_attr(mock, model_to_dict(environ))
    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)
    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):
        """Handles POST requests to create new VLAN without add NetworkIPv4.

        URLs: /vlan/no-network/
        """

        self.log.info('Create new VLAN without add NetworkIPv4')

        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('environment_id')
            name = vlan_map.get('name')
            description = vlan_map.get('description')
            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 name is invalid. Value: %s.', name)
                raise InvalidValueError(None, 'name', 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 description is invalid. Value: %s.', description)
                raise InvalidValueError(None, 'description', 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
            try:

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

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

            except AmbienteNotFoundError, e:
                self.log.error(u'The environment parameter does not exist.')
                return self.response_error(112)

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

            vlan_map = dict()
            vlan_map['vlan'] = model_to_dict(vlan)

            # Return XML
            return self.response(dumps_networkapi(vlan_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to create new VLAN without add NetworkIPv4.

        URLs: /vlan/no-network/
        """

        self.log.info('Create new VLAN without add NetworkIPv4')

        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('environment_id')
            name = vlan_map.get('name')
            description = vlan_map.get('description')
            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 name is invalid. Value: %s.', name)
                raise InvalidValueError(None, 'name', 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 description is invalid. Value: %s.', description)
                raise InvalidValueError(None, 'description', 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
            try:

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

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

            except AmbienteNotFoundError, e:
                self.log.error(u'The environment parameter does not exist.')
                return self.response_error(112)

            # 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

            #To avoid allocation same vlan number twice for different environments in same equipments
            #Lock all environments related to this environment when allocating vlan number
            #select all equipments from this environment that are not part of a filter
            # and them selects all environments from all these equipments and lock them out
            filtered_equipment_type_ids = list()

            env_filter = None
            try:
                env_filter = env.filter.id
            except:
                pass
                
            for fet in FilterEquipType.objects.filter(filter=env_filter):
                filtered_equipment_type_ids.append(fet.equiptype.id)

            filtered_environment_equips = Equipamento.objects.filter(equipamentoambiente__ambiente=env).exclude(
                tipo_equipamento__in=filtered_equipment_type_ids)

            #select all environments from the equips that were not filtered
            locks_list = list()
            environments_list = Ambiente.objects.filter(equipamentoambiente__equipamento__in=filtered_environment_equips).distinct()
            for environment in environments_list:
                lock = distributedlock(LOCK_ENVIRONMENT % environment.id)
                lock.__enter__()
                locks_list.append(lock)

            # Persist
            try:
                vlan.create_new(user,
                            min_num_01,
                            max_num_01,
                            min_num_02,
                            max_num_02
                            )
            except Exception, e:
                #release all the locks if failed
                for lock in locks_list:
                    lock.__exit__('', '', '')
                raise e
    def handle_get(self, request, user, *args, **kwargs):
        """Treat GET requests to check if a vlan need confimation to insert

        URL: vlan/confirm/
        """

        try:

            # Get XML data
            ip_version = kwargs.get("ip_version")

            if ip_version == "None":
                is_number = True
                number = kwargs.get("number")
                id_environment = kwargs.get("id_environment")
            else:
                network = kwargs.get("number")
                network = network.replace("net_replace", "/")
                id_vlan = kwargs.get("id_environment")
                if ip_version == "1":
                    version = "v6"
                else:
                    version = "v4"
                is_number = False

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

            if is_number:
                # Valid number

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

                ambiente = Ambiente.get_by_pk(id_environment)

                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)

                # Valid number
                map = dict()
                map["needs_confirmation"] = True

                for env in envs:
                    for vlan in env.vlan_set.all():
                        if int(vlan.num_vlan) == int(number):
                            if (
                                ambiente.filter_id == None
                                or vlan.ambiente.filter_id == None
                                or int(vlan.ambiente.filter_id) != int(ambiente.filter_id)
                            ):
                                map["needs_confirmation"] = False
                            else:
                                map["needs_confirmation"] = True
                                break
            else:
                # Valid subnet

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

                # Get all vlans environments from equipments of the current
                # environment
                vlan = Vlan()
                vlan = vlan.get_by_pk(id_vlan)
                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
                network = str(network)
                prefix = split(network, "/")
                net_explode = prefix[0]

                if version == IP_VERSION.IPv4[0]:
                    expl = split(net_explode, ".")
                else:
                    expl = split(net_explode, ":")

                expl.append(str(prefix[1]))

                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)

                                # Valid number
                map = dict()
                map["needs_confirmation"] = True

                # 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):
                    map["needs_confirmation"] = False
                else:
                    map["needs_confirmation"] = True

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

        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 a HeltcheckExpect.

        URL: healthcheckexpect/add/
        """

        try:
            # Business Validations

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

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            healthcheck_map = networkapi_map.get('healthcheck')
            if healthcheck_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
            match_list = healthcheck_map.get('match_list')
            expect_string = healthcheck_map.get('expect_string')
            environment_id = healthcheck_map.get('id_ambiente')

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

            if expect_string is not None:
                if not is_valid_string_maxsize(expect_string, 50) or not is_valid_string_minsize(expect_string, 2):
                    self.log.error(
                        u'Parameter expect_string is invalid. Value: %s.', expect_string)
                    raise InvalidValueError(
                        None, 'expect_string', expect_string)
            else:
                raise InvalidValueError(None, 'expect_string', expect_string)

            if match_list is not None:
                if not is_valid_string_maxsize(match_list, 50) or not is_valid_string_minsize(match_list, 2):
                    self.log.error(
                        u'Parameter match_list is invalid. Value: %s.', match_list)
                    raise InvalidValueError(None, 'match_list', match_list)
            else:
                raise InvalidValueError(None, 'expect_string', expect_string)

            # User permission
            if not has_perm(user,
                            AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            healthcheck = HealthcheckExpect()

            ambiente = Ambiente.get_by_pk(environment_id)

            healthcheck.insert(user, match_list, expect_string, ambiente)

            healtchcheck_dict = dict()
            healtchcheck_dict['id'] = healthcheck.id

            return self.response(dumps_networkapi({'healthcheck_expect': healtchcheck_dict}))

        except AmbienteNotFoundError, e:
            return self.response_error(112)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to insert vlan

        URL: vlan/insert/
        """

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

            # Commons Validations

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

            # Business Validations

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            vlan = Vlan()

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

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

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

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

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

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

            vlan.insert_vlan(user)

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

                if list_equip_routers_ambient:

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

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

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

                    ip_model.save(user)

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

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

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

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

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

                if list_equip_routers_ambient:

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

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

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

                    ipv6_model.save(user)

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

                    for equip in list_equip_routers_ambient:

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

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

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

            # Delete vlan's cache
            # destroy_cache_function()

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

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

        URL:  /ipv6/environment/
        """

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

        try:

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

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

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

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

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

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

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

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

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

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

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

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

        except UserNotAuthorizedError:
            return self.not_authorized()
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_get(self, request, user, *args, **kwargs):
        """Handles POST requests to find all Equipments by search parameters.

        URLs: /equipment/find/
        """

        self.log.info('Find all Equipments')

        try:

            # Commons Validations

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

            # Business Validations

            # Get data from URL GET parameters
            equip_name = kwargs.get('equip_name').strip()
            id_ambiente = kwargs.get('id_ambiente')

            # Business Rules

            # Start with alls
            ambiente = Ambiente.get_by_pk(id_ambiente)
             # Get Equipment
            equip = Equipamento.get_by_name(equip_name)

            lista_ips_equip = set()
            lista_ipsv6_equip = set()

            environment_vip_list = EnvironmentVip.get_environment_vips_by_environment_id(id_ambiente)
            environment_list_related = EnvironmentEnvironmentVip.get_environment_list_by_environment_vip_list(environment_vip_list)

            # # Get all IPV4's Equipment
            for environment in environment_list_related:
                for ipequip in equip.ipequipamento_set.select_related().all():
                    network_ipv4 = ipequip.ip.networkipv4
                    if network_ipv4.vlan.ambiente == environment:
                        lista_ips_equip.add(ipequip.ip)

            # # Get all IPV6's Equipment
            for environment in environment_list_related:
                for ipequip in equip.ipv6equipament_set.select_related().all():
                    network_ipv6 = ipequip.ip.networkipv6
                    if network_ipv6.vlan.ambiente == environment:
                        lista_ipsv6_equip.add(ipequip.ip)

            # lists and dicts for return
            lista_ip_entregue = list()
            lista_ip6_entregue = list()

            for ip in lista_ips_equip:
                dict_ips4 = dict()
                dict_network = dict()

                dict_ips4['id'] = ip.id
                dict_ips4['ip'] = "%s.%s.%s.%s" % (
                    ip.oct1, ip.oct2, ip.oct3, ip.oct4)

                dict_network['id'] = ip.networkipv4_id
                dict_network["network"] = "%s.%s.%s.%s" % (
                    ip.networkipv4.oct1, ip.networkipv4.oct2, ip.networkipv4.oct3, ip.networkipv4.oct4)
                dict_network["mask"] = "%s.%s.%s.%s" % (
                    ip.networkipv4.mask_oct1, ip.networkipv4.mask_oct2, ip.networkipv4.mask_oct3, ip.networkipv4.mask_oct4)

                dict_ips4['network'] = dict_network

                lista_ip_entregue.append(dict_ips4)

            for ip in lista_ipsv6_equip:
                dict_ips6 = dict()
                dict_network = dict()

                dict_ips6['id'] = ip.id
                dict_ips6['ip'] = "%s:%s:%s:%s:%s:%s:%s:%s" % (
                    ip.block1, ip.block2, ip.block3, ip.block4, ip.block5, ip.block6, ip.block7, ip.block8)

                dict_network['id'] = ip.networkipv6.id
                dict_network["network"] = "%s:%s:%s:%s:%s:%s:%s:%s" % (
                    ip.networkipv6.block1, ip.networkipv6.block2, ip.networkipv6.block3, ip.networkipv6.block4, ip.networkipv6.block5, ip.networkipv6.block6, ip.networkipv6.block7, ip.networkipv6.block8)
                dict_network["mask"] = "%s:%s:%s:%s:%s:%s:%s:%s" % (
                    ip.networkipv6.block1, ip.networkipv6.block2, ip.networkipv6.block3, ip.networkipv6.block4, ip.networkipv6.block5, ip.networkipv6.block6, ip.networkipv6.block7, ip.networkipv6.block8)

                dict_ips6['network'] = dict_network

                lista_ip6_entregue.append(dict_ips6)

            lista_ip_entregue = lista_ip_entregue if len(
                lista_ip_entregue) > 0 else None
            lista_ip6_entregue = lista_ip6_entregue if len(
                lista_ip6_entregue) > 0 else None


            return self.response(dumps_networkapi({'list_ipv4': lista_ip_entregue, 'list_ipv6': lista_ip6_entregue}))

        except InvalidValueError, e:
            self.log.error(
                u'Parameter %s is invalid. Value: %s.', e.param, e.value)
            return self.response_error(269, e.param, e.value)
def 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 handle_post(self, request, user, *args, **kwargs):
        '''Treat POST requests to edit a vlan 

        URL: vlan/edit/
        '''

        try:

            network_version = kwargs.get('network_version')

            # Commons Validations

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

            # Business Validations

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

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

            # Get XML data
            environment_id = vlan_map.get('environment_id')
            number = vlan_map.get('number')
            name = vlan_map.get('name')
            acl_file = vlan_map.get('acl_file')
            acl_file_v6 = vlan_map.get('acl_file_v6')
            description = vlan_map.get('description')
            id_vlan = vlan_map.get('vlan_id')

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

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

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

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

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

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

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

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

            vlan = Vlan()
            vlan = vlan.get_by_pk(id_vlan)

            with distributedlock(LOCK_VLAN % id_vlan):

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

                    # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                    vlan.get_vlan_by_acl(acl_file)

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

                    # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                    vlan.get_vlan_by_acl_v6(acl_file_v6)

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

                change_name = False
                change_number_environment = False

                redes4 = vlan.networkipv4_set.all()
                redes6 = vlan.networkipv6_set.all()

                listaIpsv4 = []
                listaIpsv6 = []

                listaEquips4 = []
                listaEquips6 = []

                for rede in redes4:
                    for ip in rede.ip_set.all():
                        listaIpsv4.append(ip)

                for rede in redes6:
                    for ip in rede.ipv6_set.all():
                        listaIpsv6.append(ip)

                for ip in listaIpsv4:
                    for ipequip in ip.ipequipamento_set.all():
                        listaEquips4.append(ipequip.equipamento)

                for ip in listaIpsv6:
                    for ipequip in ip.ipv6equipament_set.all():
                        listaEquips6.append(ipequip.equipamento)

                listaDeIps4DoEquip = []
                listaDeIps6DoEquip = []
                listaDeVlansDoEquip = []

                for equip in listaEquips4:
                    for ipequip in equip.ipequipamento_set.all():
                        ip_aux = ipequip.ip
                        if ip_aux not in listaDeIps4DoEquip:
                            listaDeIps4DoEquip.append(ip_aux)

                for equip in listaEquips6:
                    for ipequip in equip.ipv6equipament_set.all():
                        ip_aux = ipequip.ip
                        if ip_aux not in listaDeIps4DoEquip:
                            listaDeIps6DoEquip.append(ip_aux)

                for ip in listaDeIps4DoEquip:
                    vlan_aux = ip.networkipv4.vlan
                    if vlan_aux not in listaDeVlansDoEquip:
                        listaDeVlansDoEquip.append(vlan_aux)

                for ip in listaDeIps6DoEquip:
                    vlan_aux = ip.networkipv6.vlan
                    if vlan_aux not in listaDeVlansDoEquip:
                        listaDeVlansDoEquip.append(vlan_aux)

                if vlan.nome != name:
                    change_name = True
                    vlan.nome = name
                if int(vlan.num_vlan) != int(number) or int(vlan.ambiente.id) != int(environment_id):
                    change_number_environment = True
                    vlan.num_vlan = number
                    vlan.ambiente = ambiente

                vlan.acl_file_name = acl_file
                vlan.acl_file_name_v6 = acl_file_v6
                vlan.descricao = description

                vlan_id_cache = [id_vlan]
                # Delete vlan's cache
                destroy_cache_function(vlan_id_cache)

                # Delete equipment's cache
                equip_id_list = []

                for netv4 in vlan.networkipv4_set.all():
                    for ip in netv4.ip_set.all():
                        for ip_equip in ip.ipequipamento_set.all():
                            equip_id_list.append(ip_equip.equipamento_id)

                for netv6 in vlan.networkipv6_set.all():
                    for ip in netv6.ipv6_set.all():
                        for ip_equip in ip.ipv6equipament_set.all():
                            equip_id_list.append(ip_equip.equipamento_id)

                destroy_cache_function(equip_id_list, True)

                vlan.edit_vlan(user, change_name, change_number_environment)
                # Return XML

                return self.response(dumps_networkapi({}))

        except VlanACLDuplicatedError, e:
            return self.response_error(311, acl_file)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Rack.
        URL: channel/inserir/
        """
        try:
            self.log.info("Inserir novo Channel")

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_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.')

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

            # Get XML data
            interfaces = channel_map.get('interfaces')
            nome = channel_map.get('nome')
            lacp = channel_map.get('lacp')
            int_type = channel_map.get('int_type')
            vlans = channel_map.get('vlan')
            envs = channel_map.get('envs')

            port_channel = PortChannel()
            interface = Interface()
            amb = Ambiente()

            cont = []

            interfaces = str(interfaces).split('-')
            interface_id = None

            # verifica a vlan_nativa
            vlan = vlans.get('vlan_nativa')
            if vlan is not None:
                if int(vlan) < 1 or int(vlan) > 4096:
                    raise InvalidValueError(None, "Vlan Nativa", "Range valido: 1 - 4096.")
                if int(vlan) < 1 or 3967 < int(vlan) < 4048 or int(vlan)==4096:
                    raise InvalidValueError(None, "Vlan Nativa" ,"Range reservado: 3968-4047;4094.")

            # verifica se o nome do port channel já existe no equipamento
            channels = PortChannel.objects.filter(nome=nome)
            channels_id = []
            for ch in channels:
                channels_id.append(int(ch.id))
            if channels_id:
                for var in interfaces:
                    if not var=="" and not var==None:
                        interface_id = int(var)
                interface_id = interface.get_by_pk(interface_id)
                equip_id = interface_id.equipamento.id
                equip_interfaces = interface.search(equip_id)
                for i in equip_interfaces:
                    try:
                        sw = i.get_switch_and_router_interface_from_host_interface(i.protegida)
                    except:
                        sw = None
                        pass
                    if sw.channel is not None:
                        if sw.channel.id in channels_id:
                            raise InterfaceError("O nome do port channel ja foi utilizado no equipamento")

            #cria o port channel
            port_channel.nome = str(nome)
            port_channel.lacp = convert_string_or_int_to_boolean(lacp)
            port_channel.create(user)

            int_type = TipoInterface.get_by_name(str(int_type))

            for var in interfaces:
                if not var=="" and not var==None:
                    interf = interface.get_by_pk(int(var))

                    try:
                        sw_router = interf.get_switch_and_router_interface_from_host_interface(interf.protegida)
                    except:
                        raise InterfaceError("Interface não conectada")

                    if sw_router.channel is not None:
                        raise InterfaceError("Interface %s já está em um Channel" % sw_router.interface)

                    if cont is []:
                        cont.append(int(sw_router.equipamento.id))
                    elif not sw_router.equipamento.id in cont:
                        cont.append(int(sw_router.equipamento.id))
                        if len(cont) > 2:
                            raise InterfaceError("Mais de dois equipamentos foram selecionados")

                    if sw_router.ligacao_front is not None:
                        ligacao_front_id = sw_router.ligacao_front.id
                    else:
                        ligacao_front_id = None
                    if sw_router.ligacao_back is not None:
                        ligacao_back_id = sw_router.ligacao_back.id
                    else:
                        ligacao_back_id = None

                    Interface.update(user,
                                     sw_router.id,
                                     interface=sw_router.interface,
                                     protegida=sw_router.protegida,
                                     descricao=sw_router.descricao,
                                     ligacao_front_id=ligacao_front_id,
                                     ligacao_back_id=ligacao_back_id,
                                     tipo=int_type,
                                     vlan_nativa=vlans.get('vlan_nativa'),
                                     channel=port_channel)

                    if "trunk" in int_type.tipo:
                        interface_list = EnvironmentInterface.objects.all().filter(interface=sw_router.id)
                        for int_env in interface_list:
                            int_env.delete()
                        if envs is not None:
                            amb = amb.get_by_pk(int(envs))
                            amb_int = EnvironmentInterface()
                            amb_int.interface = sw_router
                            amb_int.ambiente = amb
                            try:
                                range_vlans = vlans.get('range')
                            except:
                                range_vlans = None
                                pass
                            if range_vlans:
                                api_interface_facade.verificar_vlan_range(amb, range_vlans)
                                amb_int.vlans = range_vlans
                            amb_int.create(user)

            port_channel_map = dict()
            port_channel_map['port_channel'] = port_channel

            return self.response(dumps_networkapi({'port_channel': port_channel_map}))

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