def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to edit Access Type.

        URL: /tipoacesso/<id_tipo_acesso>/

        """

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

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

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get("networkapi")
            if networkapi_map is None:
                return self.response_error(3, u"There is no networkapi tag in request XML.")

            tipo_acesso_map = networkapi_map.get("tipo_acesso")
            if tipo_acesso_map is None:
                return self.response_error(3, u"There is no tipo_acesso tag in request XML.")

            # Valid protocol
            protocol = tipo_acesso_map.get("protocolo")
            if (
                not is_valid_string_minsize(protocol, 3)
                or not is_valid_string_maxsize(protocol, 45)
                or not is_valid_regex(protocol, r"^[- a-zA-Z0-9]+$")
            ):
                self.log.error(u"Parameter protocol is invalid. Value: %s", protocol)
                raise InvalidValueError(None, "protocol", protocol)

            # Verify existence
            tpa = TipoAcesso.get_by_pk(tipo_acesso_id)

            tpa.protocolo = protocol

            try:
                if len(TipoAcesso.objects.filter(protocolo__iexact=protocol).exclude(id=tpa.id)) > 0:
                    raise DuplicateProtocolError(None, u"Access Type with protocol %s already exists" % protocol)
            except TipoAcesso.DoesNotExist:
                pass

            with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id):

                try:
                    # save access type
                    tpa.save(user)
                except Exception, e:
                    self.log.error(u"Failed to update TipoAcesso.")
                    raise TipoAcessoError(e, u"Failed to update TipoAcesso.")

            return self.response(dumps_networkapi({}))
Ejemplo n.º 2
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Access Type.

        URL: /tipoacesso/

        """

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

            xml_map, attrs_map = loads(request.raw_post_data)

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

            tipo_acesso_map = networkapi_map.get('tipo_acesso')
            if tipo_acesso_map is None:
                return self.response_error(
                    3, u'There is no tipo_acesso tag in request XML.')

            # Valid protocol
            protocol = tipo_acesso_map.get('protocolo')
            if not is_valid_string_minsize(
                    protocol, 3) or not is_valid_string_maxsize(
                        protocol, 45) or not is_valid_regex(
                            protocol, r'^[- a-zA-Z0-9]+$'):
                self.log.error(u'Parameter protocol is invalid. Value: %s',
                               protocol)
                raise InvalidValueError(None, 'protocol', protocol)

            access_type = TipoAcesso()
            access_type.protocolo = protocol

            try:
                TipoAcesso.objects.get(protocolo__iexact=access_type.protocolo)
                raise DuplicateProtocolError(
                    None,
                    u'Access Type with protocol %s already exists' % protocol)
            except TipoAcesso.DoesNotExist:
                pass

            try:
                # save access type
                access_type.save()
            except Exception, e:
                self.log.error(u'Failed to save TipoAcesso.')
                raise TipoAcessoError(e, u'Failed to save TipoAcesso.')

            return self.response(
                dumps_networkapi({'tipo_acesso': {
                    'id': access_type.id
                }}))
Ejemplo n.º 3
0
    def create(self, authenticated_user):
        """Add new port channel"""

        # Checks if name is valid
        try:
            if not is_valid_regex(self.nome, "[a-zA-Z\-]+[0-9]+$"):
                raise InvalidValueError(None, 'nome', self.nome)
        except Exception, e:
            raise InvalidValueError(None, e.param, e.value)
Ejemplo n.º 4
0
    def update(cls, authenticated_user, id_interface, **kwargs):
        """Update interface according to arguments

        @param id_interface: Interface identifier 

        @return: Interface instance

        @raise InterfaceNotFoundError: Interface doesn't exist
        @raise FrontLinkNotFoundError: FrontEnd connection Interface doesn't exist
        @raise BackLinkNotFoundError: BackEnd connection Interface doesn't exist
        @raise InterfaceForEquipmentDuplicatedError: An interface with the same name on the same equipment already exists
        @raise InterfaceError: Failed to update interface
        """

        # Get interface
        interface = Interface.get_by_pk(id_interface)

        nome = kwargs['interface']
        marca = interface.equipamento.modelo.marca.id if interface.equipamento.tipo_equipamento.id != 2 else 0


        if marca == 0:
            regex = "^([a-zA-Z0-9-_/ ]+(:)?){1,6}$"
        elif marca == 2:
            regex = "^(Int)\s[0-9]+$"
        elif marca == 3:
            regex = "^(Fa|Gi|Te|Serial|Eth|mgmt)\s?[0-9]+(/[0-9]+(/[0-9]+)?)?$"
        elif marca == 4:
            regex = "^(interface)\s[0-9]+(/[0-9]+.[0-9]+)?$"
        elif marca == 5:
            regex = "^(eth)[0-9]+(/[0-9]+)?$"
        elif marca == 8:
            regex = "^[0-9]+$"
        else:
            regex = ""

        # Checks if name is valid according to the brand
        if not is_valid_regex(nome, regex):
            raise InvalidValueError(None, 'nome', nome)

        # Valid ligacao_front_id
        try:
            id_ligacao_front = kwargs['ligacao_front_id']
            if id_ligacao_front is not None:
                if (interface.ligacao_front_id != id_ligacao_front):
                    interface.ligacao_front = Interface.get_by_pk(
                        id_ligacao_front)
            else:
                interface.ligacao_front = None
        except InterfaceNotFoundError, e:
            raise FrontLinkNotFoundError(
                e, u'Frontend interface does not exist')
Ejemplo n.º 5
0
    def create_v3(self, interface):
        """
        Add new interface

        @return: Interface instance
        @raise EquipamentoNotFoundError: Equipment doesn't exist
        @raise EquipamentoError: Failed to find equipment
        @raise FrontLinkNotFoundError: FrontEnd interface doesn't exist
        @raise BackLinkNotFoundError: BackEnd interface doesn't exist
        @raise InterfaceForEquipmentDuplicatedError: An interface with the same name on the same
        equipment already exists
        @raise InterfaceError: Failed to add new interface
        """

        # validate interface name
        if Interface.objects.filter(
                equipamento__id=interface.get('equipment_id'),
                interface__iexact=interface.get('name')):
            raise InterfaceForEquipmentDuplicatedError(
                None, u'Duplicate interface name for the device.')

        self.tipo = TipoInterface.get_by_pk(interface.get('type'))

        self.equipamento = facade.get_equipment_by_id(
            interface.get('equipment_id'))

        marca = self.equipamento.modelo.marca.id if self.equipamento.tipo_equipamento.id != 2 else 0

        if marca == 0:
            regex = '^([a-zA-Z0-9-_/ ]+(:)?){1,6}$'
        elif marca == 2:
            regex = '^(Int)\s[0-9]+$'
        elif marca == 3:
            regex = '^(Fa|Gi|Te|Serial|Eth|mgmt)\s?[0-9]+(/[0-9]+(/[0-9]+)?)?$'
        elif marca == 4:
            regex = '^(interface)\s[0-9a-zA-Z]+(/[0-9a-zA-Z])+([0-9a-zA-Z-.]+)?$'
        elif marca == 5:
            regex = '^(eth)[0-9]+(/[0-9]+)?$'
        else:
            regex = ''

        # Validate if interface name conforms to the brand
        if not is_valid_regex(self.interface, regex):
            raise InvalidValueError(None, 'nome', self.interface)

        try:
            self.ligacao_front = Interface.get_by_pk(interface.get('front_connection_id')) \
                if interface.get('front_connection_id') else None
        except InterfaceNotFoundError, e:
            raise FrontLinkNotFoundError(e,
                                         u'Frontend interface does not exist')
    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Access Type.

        URL: /tipoacesso/

        """

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

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get("networkapi")
            if networkapi_map is None:
                return self.response_error(3, u"There is no networkapi tag in request XML.")

            tipo_acesso_map = networkapi_map.get("tipo_acesso")
            if tipo_acesso_map is None:
                return self.response_error(3, u"There is no tipo_acesso tag in request XML.")

            # Valid protocol
            protocol = tipo_acesso_map.get("protocolo")
            if (
                not is_valid_string_minsize(protocol, 3)
                or not is_valid_string_maxsize(protocol, 45)
                or not is_valid_regex(protocol, r"^[- a-zA-Z0-9]+$")
            ):
                self.log.error(u"Parameter protocol is invalid. Value: %s", protocol)
                raise InvalidValueError(None, "protocol", protocol)

            access_type = TipoAcesso()
            access_type.protocolo = protocol

            try:
                TipoAcesso.objects.get(protocolo__iexact=access_type.protocolo)
                raise DuplicateProtocolError(None, u"Access Type with protocol %s already exists" % protocol)
            except TipoAcesso.DoesNotExist:
                pass

            try:
                # save access type
                access_type.save(user)
            except Exception, e:
                self.log.error(u"Failed to save TipoAcesso.")
                raise TipoAcessoError(e, u"Failed to save TipoAcesso.")

            return self.response(dumps_networkapi({"tipo_acesso": {"id": access_type.id}}))
Ejemplo n.º 7
0
    def update(cls, authenticated_user, id_interface, **kwargs):
        """Update interface according to arguments

        @param id_interface: Interface identifier

        @return: Interface instance

        @raise InterfaceNotFoundError: Interface doesn't exist
        @raise FrontLinkNotFoundError: FrontEnd connection Interface doesn't exist
        @raise BackLinkNotFoundError: BackEnd connection Interface doesn't exist
        @raise InterfaceForEquipmentDuplicatedError: An interface with the same name on the same equipment already exists
        @raise InterfaceError: Failed to update interface
        """

        # Get interface
        interface = Interface.get_by_pk(id_interface)
        nome = kwargs['interface']
        marca = interface.equipamento.modelo.marca.id if interface.equipamento.tipo_equipamento.id != 2 else 0

        if marca == 0:
            regex = '^([a-zA-Z0-9-_/ ]+(:)?){1,6}$'
        elif marca == 2:
            regex = '^(Int)\s[0-9]+$'
        elif marca == 3:
            regex = '^(Fa|Gi|Te|Serial|Eth|mgmt)\s?[0-9]+(/[0-9]+(/[0-9]+)?)?$'
        elif marca == 4:
            regex = '^(interface)\s[0-9]+(/[0-9]+.[0-9]+)?$'
        elif marca == 5:
            regex = '^(eth)[0-9]+(/[0-9]+)?$'
        elif marca == 8:
            regex = '^[0-9]+$'
        else:
            regex = ''

        # Checks if name is valid according to the brand
        if not is_valid_regex(nome, regex):
            raise InvalidValueError(None, 'nome', nome)
        # Valid ligacao_front_id
        try:
            id_ligacao_front = kwargs['ligacao_front_id']
            if id_ligacao_front is not None:
                if (interface.ligacao_front_id != id_ligacao_front):
                    interface.ligacao_front = Interface.get_by_pk(
                        id_ligacao_front)
            else:
                interface.ligacao_front = None
        except InterfaceNotFoundError, e:
            raise FrontLinkNotFoundError(e,
                                         u'Frontend interface does not exist')
def fix_acl_path(acl_path):
    path = acl_path
    if path:
        if is_valid_regex(path, r'^.*[\\\\:*?"<>|].*$'):
            raise InvalidValueError(None, 'acl_path', acl_path)
        try:
            while path[0] == '/':
                path = path[1:]

            while path[-1] == '/':
                path = path[:-1]
        except IndexError:
            raise InvalidValueError(None, 'acl_path', acl_path)

    return path
Ejemplo n.º 9
0
def fix_acl_path(acl_path):
    path = acl_path
    if path:
        if is_valid_regex(path, r'^.*[\\\\:*?"<>|].*$'):
            raise InvalidValueError(None, 'acl_path', acl_path)
        try:
            while path[0] == '/':
                path = path[1:]

            while path[-1] == '/':
                path = path[:-1]
        except IndexError:
            raise InvalidValueError(None, 'acl_path', acl_path)

    return path
Ejemplo n.º 10
0
    def create(self, authenticated_user):
        """Add new interface

        @param authenticated_user: User Authentication
        @return: Interface instance

        @raise EquipamentoNotFoundError: Equipment doesn't exist
        @raise EquipamentoError: Failed to find equipment
        @raise FrontLinkNotFoundError: FrontEnd interface doesn't exist
        @raise BackLinkNotFoundError: BackEnd interface doesn't exist
        @raise InterfaceForEquipmentDuplicatedError: An interface with the same name on the same
        equipment already exists
        @raise InterfaceError: Failed to add new interface
        """

        # Valid equipment
        self.equipamento = Equipamento.get_by_pk(self.equipamento.id)

        marca = self.equipamento.modelo.marca.id if self.equipamento.tipo_equipamento.id != 2 else 0

        if marca == 0:
            regex = '^([a-zA-Z0-9-_/ ]+(:)?){1,6}$'
        elif marca == 2:
            regex = '^(Int)\s[0-9]+$'
        elif marca == 3:
            regex = '^(Fa|Gi|Te|Serial|Eth|mgmt)\s?[0-9]+(/[0-9]+(/[0-9]+)?)?$'
        elif marca == 4:
            regex = '^(interface)\s[0-9a-zA-Z]+(/[0-9a-zA-Z])+([0-9a-zA-Z-.]+)?$'
        elif marca == 5:
            regex = '^(eth)[0-9]+(/[0-9]+)?$'
        else:
            regex = ''

        # Checks if name is valid according to the brand
        if not is_valid_regex(self.interface, regex):
            raise InvalidValueError(None, 'nome', self.interface)

        # Check front end interface existence
        if self.ligacao_front is not None:
            try:
                self.ligacao_front = Interface.get_by_pk(self.ligacao_front.id)
            except InterfaceNotFoundError, e:
                raise FrontLinkNotFoundError(
                    e, u'Frontend interface does not exist')
Ejemplo n.º 11
0
    def create(self, authenticated_user):
        """Add new interface

        @return: Interface instance

        @raise EquipamentoNotFoundError: Equipment doesn't exist
        @raise EquipamentoError: Failed to find equipment 
        @raise FrontLinkNotFoundError: FrontEnd interface doesn't exist
        @raise BackLinkNotFoundError: BackEnd interface doesn't exist
        @raise InterfaceForEquipmentDuplicatedError: An interface with the same name on the same equipment already exists
        @raise InterfaceError: Failed to add new interface
        """

        # Valid equipment
        self.equipamento = Equipamento.get_by_pk(self.equipamento.id)

        marca = self.equipamento.modelo.marca.id if self.equipamento.tipo_equipamento.id != 2 else 0

        if marca == 0:
            regex = "^([a-zA-Z0-9-_/ ]+(:)?){1,6}$"
        elif marca == 2:
            regex = "^(Int)\s[0-9]+$"
        elif marca == 3:
            regex = "^(Fa|Gi|Te|Serial|Eth|mgmt)\s?[0-9]+(/[0-9]+(/[0-9]+)?)?$"
        elif marca == 4:
            regex = "^(interface)\s[0-9a-zA-Z]+(/[0-9a-zA-Z])+([0-9a-zA-Z-.]+)?$"
        elif marca == 5:
            regex = "^(eth)[0-9]+(/[0-9]+)?$"
        elif marca == 8:
            regex = "^[0-9]+$"
        else:
            regex = ""

        # Checks if name is valid according to the brand
        if not is_valid_regex(self.interface, regex):
            raise InvalidValueError(None, 'nome', self.interface)

        # Check front end interface existence
        if self.ligacao_front is not None:
            try:
                self.ligacao_front = Interface.get_by_pk(self.ligacao_front.id)
            except InterfaceNotFoundError, e:
                raise FrontLinkNotFoundError(
                    e, u'Frontend interface does not exist')
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to valid Real server.

        URL: vip/real/valid/
        '''
        self.log.info('Valid Real Server')

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

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

            # Get XML data
            ip = real_map.get('ip')
            name = real_map.get('name_equipment')
            id_evip = real_map.get('id_environment_vip')
            valid = real_map.get('valid')

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

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

            # Valid Name Equipment
            if not is_valid_string_minsize(
                    name, 3) or not is_valid_string_maxsize(
                        name, 80) or not is_valid_regex(name, "^[A-Z0-9-_]+$"):
                self.log.error(
                    u'Parameter name_equipment is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name_equipment', name)

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

            # Valid Equipment
            equip = Equipamento.get_by_name(name)

            # Valid EnvironmentVip
            evip = EnvironmentVip.get_by_pk(id_evip)

            version = ""
            if is_valid_ipv4(ip):
                version = IP_VERSION.IPv4[1]

            elif is_valid_ipv6(ip):
                version = IP_VERSION.IPv6[1]

            ip, equip, evip = RequisicaoVips.valid_real_server(
                ip, equip, evip, valid)

            real_dict = {}
            ip_dict = model_to_dict(ip)
            ip_dict["version"] = version

            real_dict["ip"] = ip_dict
            real_dict["equipment"] = model_to_dict(equip)
            real_dict["environmentvip"] = model_to_dict(evip)

            return self.response(dumps_networkapi({'real': real_dict}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
    def handle_post(self, request, user, *args, **kwargs):
        """Trata uma requisicao POST para editar um equipamento.

        URL: equipmento/edit/
        """
        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

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

            # Get XML data
            equip_id = equip_map.get('id_equip')
            id_modelo = equip_map.get('id_modelo')
            nome = equip_map.get('nome')
            id_tipo_equipamento = equip_map.get('id_tipo_equipamento')
            maintenance = equip_map.get('maintenance')

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

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

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

            # Valid nome
            if not is_valid_string_minsize(
                    nome, 3) or not is_valid_string_maxsize(
                        nome, 80) or not is_valid_regex(nome, '^[A-Z0-9-_]+$'):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)

            # Business Rules

            # New equipment
            equip = Equipamento()
            equip = equip.get_by_pk(equip_id)

            # maintenance is a new feature. Check existing value if not defined in request
            # Old calls does not send this field
            if maintenance is None:
                maintenance = equip.maintenance
            if not is_valid_boolean_param(maintenance):
                self.log.error(
                    u'The maintenance parameter is not a valid value: %s.',
                    maintenance)
                raise InvalidValueError(None, 'maintenance', maintenance)

            if maintenance in ['1', 'True', True]:
                maintenance = True
            else:
                maintenance = False

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

            with distributedlock(LOCK_EQUIPMENT % equip_id):
                tipo_equip = TipoEquipamento.get_by_pk(id_tipo_equipamento)

                if equip.tipo_equipamento != tipo_equip:
                    # Environments with filters using current equip type, with
                    # equipment associated
                    envs = [
                        eq_env.ambiente.id
                        for eq_env in equip.equipamentoambiente_set.filter(
                            ambiente__filter__filterequiptype__equiptype=equip.
                            tipo_equipamento)
                    ]

                    # Filters case 1 and 2

                    filters_ok = True

                    # Networks in environments with same ip range
                    nets_same_range = NetworkIPv4.objects.filter(
                        vlan__ambiente__in=envs).values(
                            'oct1', 'oct2', 'oct3', 'oct4', 'block').annotate(
                                count=Count('id')).filter(count__gt=1)

                    if len(nets_same_range) > 0:
                        for net_gp in nets_same_range:
                            nets_current_range = NetworkIPv4.objects.filter(
                                vlan__ambiente__in=envs,
                                oct1=net_gp['oct1'],
                                oct2=net_gp['oct2'],
                                oct3=net_gp['oct3'],
                                oct4=net_gp['oct4'],
                                block=net_gp['block'])
                            filters_of_envs = [
                                net.vlan.ambiente.filter.id
                                for net in nets_current_range
                            ]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(
                                        id=id_tipo_equipamento,
                                        filterequiptype__filter=fil_).count(
                                        ) == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.'
                                )

                    # Networks ipv6 in environments with same ipv6 range
                    nets_v6_same_range = NetworkIPv6.objects.filter(
                        vlan__ambiente__in=envs).values(
                            'block1', 'block2', 'block3', 'block4', 'block5',
                            'block6', 'block7', 'block8', 'block').annotate(
                                count=Count('id')).filter(count__gt=1)

                    if len(nets_v6_same_range) > 0:
                        for net_gp in nets_v6_same_range:
                            nets_current_range = NetworkIPv6.objects.filter(
                                vlan__ambiente__in=envs,
                                block1=net_gp['block1'],
                                block2=net_gp['block2'],
                                block3=net_gp['block3'],
                                block4=net_gp['block4'],
                                block5=net_gp['block5'],
                                block6=net_gp['block6'],
                                block7=net_gp['block7'],
                                block8=net_gp['block8'],
                                block=net_gp['block'])
                            filters_of_envs = [
                                net.vlan.ambiente.filter.id
                                for net in nets_current_range
                            ]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(
                                        id=id_tipo_equipamento,
                                        filterequiptype__filter=fil_).count(
                                        ) == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.'
                                )

                    # Filters case 1 and 2 end

                    # Filter case 3

                    # Get vlans with same number
                    vlans_same_number = Vlan.objects.filter(
                        ambiente__in=envs).values('num_vlan').annotate(
                            count=Count('id')).filter(count__gt=1)

                    if len(vlans_same_number) > 0:
                        for vlan_gp in vlans_same_number:
                            vlans_current_number = Vlan.objects.filter(
                                ambiente__in=envs,
                                num_vlan=vlan_gp['num_vlan'])
                            filters_of_envs = [
                                vlan.ambiente.filter.id
                                for vlan in vlans_current_number
                            ]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(
                                        id=id_tipo_equipamento,
                                        filterequiptype__filter=fil_).count(
                                        ) == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.'
                                )

                    # Filter case 3 end

                    # Test all vip requests if equip.tipo_equipamento is
                    # balancing

                    if equip.tipo_equipamento == TipoEquipamento.get_tipo_balanceador(
                    ):
                        vips = RequisicaoVips.objects.all()
                        vip_ips = []
                        vip_ipsv6 = []
                        for vip in vips:
                            if vip.vip_criado:
                                if vip.ip is not None:
                                    if vip.ip.ipequipamento_set.filter(
                                            equipamento=equip.id).count() > 0:
                                        raise EquipTypeCantBeChangedError(
                                            None,
                                            'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.'
                                            % vip.id)
                                if vip.ipv6 is not None:
                                    if vip.ipv6.ipv6equipament_set.filter(
                                            equipamento=equip.id).count() > 0:
                                        raise EquipTypeCantBeChangedError(
                                            None,
                                            'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.'
                                            % vip.id)

                            else:
                                if vip.ip is not None:
                                    vip_ips.append(vip.ip.id)
                                if vip.ipv6 is not None:
                                    vip_ipsv6.append(vip.ipv6.id)

                        nets_using_balancer_in_vips_ = [
                            ip_.networkipv4
                            for ip_ in Ip.objects.filter(id__in=vip_ips)
                        ]
                        nets_using_balancer_in_vips = [
                            ip_.networkipv4 for ip_ in Ip.objects.filter(
                                networkipv4__in=nets_using_balancer_in_vips_,
                                ipequipamento__equipamento=equip.id)
                        ]
                        nets_v6_using_balancer_in_vips_ = [
                            ip_.networkipv6
                            for ip_ in Ipv6.objects.filter(id__in=vip_ipsv6)
                        ]
                        nets_v6_using_balancer_in_vips = [
                            ip_.networkipv6 for ip_ in Ipv6.objects.filter(
                                networkipv6__in=nets_v6_using_balancer_in_vips_,
                                ipv6equipament__equipamento=equip.id)
                        ]

                        for net in nets_using_balancer_in_vips:
                            net_str = str(net.oct1) + '.' + str(net.oct2) + '.' + \
                                str(net.oct3) + '.' + str(net.oct4) + \
                                '/' + str(net.block)
                            if IpEquipamento.objects.filter(
                                    ip__networkipv4=net,
                                    equipamento__tipo_equipamento=TipoEquipamento
                                    .get_tipo_balanceador()).exclude(
                                        equipamento=equip).count() == 0:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.'
                                    % (net_str, net.vlan.nome))

                        for net in nets_v6_using_balancer_in_vips:
                            net_str = str(net.block1) + ':' + str(
                                net.block2
                            ) + ':' + str(net.block3) + ':' + str(
                                net.block4) + ':' + str(
                                    net.block5) + ':' + str(
                                        net.block6) + ':' + str(
                                            net.block7) + ':' + str(
                                                net.block8) + '/' + str(
                                                    net.block)
                            if Ipv6Equipament.objects.filter(
                                    ip__networkipv6=net,
                                    equipamento__tipo_equipamento=TipoEquipamento
                                    .get_tipo_balanceador()).exclude(
                                        equipamento=equip).count() == 0:
                                raise EquipTypeCantBeChangedError(
                                    None,
                                    'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.'
                                    % (net_str, net.vlan.nome))

                ip_equipamento_list = IpEquipamento.objects.filter(
                    equipamento=equip_id)
                ip6_equipamento_list = Ipv6Equipament.objects.filter(
                    equipamento=equip_id)

                # Delete vlan's cache
                key_list = []
                for eq in ip_equipamento_list:
                    vlan = eq.ip.networkipv4.vlan
                    vlan_id = vlan.id
                    key_list.append(vlan_id)

                for eq in ip6_equipamento_list:
                    vlan = eq.ip.networkipv6.vlan
                    vlan_id = vlan.id
                    key_list.append(vlan_id)

                destroy_cache_function(key_list)

                # Delete equipment's cache
                destroy_cache_function([equip_id], True)

                modelo = Modelo.get_by_pk(id_modelo)
                equip.edit(user, nome, tipo_equip, modelo, maintenance)

                return self.response(dumps_networkapi({}))

        except EquipTypeCantBeChangedError, e:
            return self.response_error(150, e.message)
Ejemplo n.º 14
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to edit Access Type.

        URL: /tipoacesso/<id_tipo_acesso>/

        """

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

            # Valid Access Type ID
            tipo_acesso_id = kwargs.get('id_tipo_acesso')
            if not is_valid_int_greater_zero_param(tipo_acesso_id):
                self.log.error(
                    u'The tipo_acesso_id parameter is not a valid value: %s.',
                    tipo_acesso_id)
                raise InvalidValueError(None, 'tipo_acesso_id', tipo_acesso_id)

            xml_map, attrs_map = loads(request.raw_post_data)

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

            tipo_acesso_map = networkapi_map.get('tipo_acesso')
            if tipo_acesso_map is None:
                return self.response_error(
                    3, u'There is no tipo_acesso tag in request XML.')

            # Valid protocol
            protocol = tipo_acesso_map.get('protocolo')
            if not is_valid_string_minsize(
                    protocol, 3) or not is_valid_string_maxsize(
                        protocol, 45) or not is_valid_regex(
                            protocol, r'^[- a-zA-Z0-9]+$'):
                self.log.error(u'Parameter protocol is invalid. Value: %s',
                               protocol)
                raise InvalidValueError(None, 'protocol', protocol)

            # Verify existence
            tpa = TipoAcesso.get_by_pk(tipo_acesso_id)

            tpa.protocolo = protocol

            try:
                if len(
                        TipoAcesso.objects.filter(
                            protocolo__iexact=protocol).exclude(
                                id=tpa.id)) > 0:
                    raise DuplicateProtocolError(
                        None, u'Access Type with protocol %s already exists' %
                        protocol)
            except TipoAcesso.DoesNotExist:
                pass

            with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id):

                try:
                    # save access type
                    tpa.save()
                except Exception, e:
                    self.log.error(u'Failed to update TipoAcesso.')
                    raise TipoAcessoError(e, u'Failed to update TipoAcesso.')

            return self.response(dumps_networkapi({}))
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to valid Real server.

        URL: vip/real/valid/
        """
        self.log.info('Valid Real Server')

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

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

            # Get XML data
            ip = real_map.get('ip')
            name = real_map.get('name_equipment')
            id_evip = real_map.get('id_environment_vip')
            valid = real_map.get('valid')

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

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

            # Valid Name Equipment
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 80) or not is_valid_regex(name, '^[A-Z0-9-_]+$'):
                self.log.error(
                    u'Parameter name_equipment is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name_equipment', name)

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

            # Valid Equipment
            equip = Equipamento.get_by_name(name)

            # Valid EnvironmentVip
            evip = EnvironmentVip.get_by_pk(id_evip)

            version = ''
            if is_valid_ipv4(ip):
                version = IP_VERSION.IPv4[1]

            elif is_valid_ipv6(ip):
                version = IP_VERSION.IPv6[1]

            ip, equip, evip = RequisicaoVips.valid_real_server(
                ip, equip, evip, valid)

            real_dict = {}
            ip_dict = model_to_dict(ip)
            ip_dict['version'] = version

            real_dict['ip'] = ip_dict
            real_dict['equipment'] = model_to_dict(equip)
            real_dict['environmentvip'] = model_to_dict(evip)

            return self.response(dumps_networkapi({'real': real_dict}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to insert a Equipment Type.

        URL: equipmenttype/
        """

        try:

            self.log.info("Add Equipment Script")

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

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

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

            # Valid Name
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100) or not is_valid_regex(name, "^[A-Za-z0-9 -]+$"):
                self.log.error(u'Parameter name is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name', name)

            # Business Rules
            equipment_type = TipoEquipamento()

            # save Equipment Type
            equipment_type.insert_new(user, name)

            etype_dict = dict()
            etype_dict['id'] = equipment_type.id

            return self.response(dumps_networkapi({'equipment_type': etype_dict}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to insert a Equipment Type.

        URL: equipmenttype/
        """

        try:

            self.log.info("Add Equipment Script")

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

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

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

            # Valid Name
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100) or not is_valid_regex(name, "^[A-Za-z0-9 -]+$"):
                self.log.error(u'Parameter name is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name', name)

            # Business Rules
            equipment_type = TipoEquipamento()

            # save Equipment Type
            equipment_type.insert_new(user, name)

            etype_dict = dict()
            etype_dict['id'] = equipment_type.id

            return self.response(dumps_networkapi({'equipment_type': etype_dict}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        """Trata uma requisicao POST para editar um equipamento.

        URL: equipmento/edit/
        """

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

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

            # Get XML data
            equip_id = equip_map.get('id_equip')
            id_modelo = equip_map.get('id_modelo')
            nome = equip_map.get('nome')
            id_tipo_equipamento = equip_map.get('id_tipo_equipamento')
            maintenance = equip_map.get('maintenance')

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

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

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

            # Valid nome
            if not is_valid_string_minsize(nome, 3) or not is_valid_string_maxsize(nome, 80) or not is_valid_regex(nome, "^[A-Z0-9-_]+$"):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)


            # Business Rules

            # New equipment
            equip = Equipamento()
            equip = equip.get_by_pk(equip_id)

            #maintenance is a new feature. Check existing value if not defined in request
            #Old calls does not send this field
            if maintenance is None:
                maintenance = equip.maintenance
            if not is_valid_boolean_param(maintenance):
                self.log.error(u'The maintenance parameter is not a valid value: %s.', maintenance)
                raise InvalidValueError(None, 'maintenance', maintenance)

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

            with distributedlock(LOCK_EQUIPMENT % equip_id):
                tipo_equip = TipoEquipamento.get_by_pk(id_tipo_equipamento)

                if equip.tipo_equipamento != tipo_equip:
                    # Environments with filters using current equip type, with
                    # equipment associated
                    envs = [eq_env.ambiente.id for eq_env in equip.equipamentoambiente_set.filter(
                        ambiente__filter__filterequiptype__equiptype=equip.tipo_equipamento)]

                    # Filters case 1 and 2

                    filters_ok = True

                    # Networks in environments with same ip range
                    nets_same_range = NetworkIPv4.objects.filter(vlan__ambiente__in=envs).values(
                        'oct1', 'oct2', 'oct3', 'oct4', 'block').annotate(count=Count('id')).filter(count__gt=1)

                    if len(nets_same_range) > 0:
                        for net_gp in nets_same_range:
                            nets_current_range = NetworkIPv4.objects.filter(vlan__ambiente__in=envs, oct1=net_gp[
                                                                            'oct1'], oct2=net_gp['oct2'], oct3=net_gp['oct3'], oct4=net_gp['oct4'], block=net_gp['block'])
                            filters_of_envs = [
                                net.vlan.ambiente.filter.id for net in nets_current_range]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')

                    # Networks ipv6 in environments with same ipv6 range
                    nets_v6_same_range = NetworkIPv6.objects.filter(vlan__ambiente__in=envs).values(
                        'block1', 'block2', 'block3', 'block4', 'block5', 'block6', 'block7', 'block8', 'block').annotate(count=Count('id')).filter(count__gt=1)

                    if len(nets_v6_same_range) > 0:
                        for net_gp in nets_v6_same_range:
                            nets_current_range = NetworkIPv6.objects.filter(vlan__ambiente__in=envs, block1=net_gp['block1'], block2=net_gp['block2'], block3=net_gp[
                                                                            'block3'], block4=net_gp['block4'], block5=net_gp['block5'], block6=net_gp['block6'], block7=net_gp['block7'], block8=net_gp['block8'], block=net_gp['block'])
                            filters_of_envs = [
                                net.vlan.ambiente.filter.id for net in nets_current_range]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')

                    # Filters case 1 and 2 end

                    # Filter case 3

                    # Get vlans with same number
                    vlans_same_number = Vlan.objects.filter(ambiente__in=envs).values(
                        'num_vlan').annotate(count=Count('id')).filter(count__gt=1)

                    if len(vlans_same_number) > 0:
                        for vlan_gp in vlans_same_number:
                            vlans_current_number = Vlan.objects.filter(
                                ambiente__in=envs, num_vlan=vlan_gp['num_vlan'])
                            filters_of_envs = [
                                vlan.ambiente.filter.id for vlan in vlans_current_number]
                            for fil_ in filters_of_envs:
                                if TipoEquipamento.objects.filter(id=id_tipo_equipamento, filterequiptype__filter=fil_).count() == 0:
                                    filters_ok = False
                                    break

                            if not filters_ok:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois existe um filtro em uso que não possui o novo tipo de equipamento informado.')

                    # Filter case 3 end

                    # Test all vip requests if equip.tipo_equipamento is
                    # balancing

                    if equip.tipo_equipamento == TipoEquipamento.get_tipo_balanceador():
                        vips = RequisicaoVips.objects.all()
                        vip_ips = []
                        vip_ipsv6 = []
                        for vip in vips:
                            if vip.vip_criado:
                                if vip.ip is not None:
                                    if vip.ip.ipequipamento_set.filter(equipamento=equip.id).count() > 0:
                                        raise EquipTypeCantBeChangedError(
                                            None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.' % vip.id)
                                if vip.ipv6 is not None:
                                    if vip.ipv6.ipv6equipament_set.filter(equipamento=equip.id).count() > 0:
                                        raise EquipTypeCantBeChangedError(
                                            None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o balanceador associado com o vip criado %s.' % vip.id)

                            else:
                                if vip.ip is not None:
                                    vip_ips.append(vip.ip.id)
                                if vip.ipv6 is not None:
                                    vip_ipsv6.append(vip.ipv6.id)

                        nets_using_balancer_in_vips_ = [
                            ip_.networkipv4 for ip_ in Ip.objects.filter(id__in=vip_ips)]
                        nets_using_balancer_in_vips = [ip_.networkipv4 for ip_ in Ip.objects.filter(
                            networkipv4__in=nets_using_balancer_in_vips_, ipequipamento__equipamento=equip.id)]
                        nets_v6_using_balancer_in_vips_ = [
                            ip_.networkipv6 for ip_ in Ipv6.objects.filter(id__in=vip_ipsv6)]
                        nets_v6_using_balancer_in_vips = [ip_.networkipv6 for ip_ in Ipv6.objects.filter(
                            networkipv6__in=nets_v6_using_balancer_in_vips_, ipv6equipament__equipamento=equip.id)]

                        for net in nets_using_balancer_in_vips:
                            net_str = str(net.oct1) + '.' + str(net.oct2) + '.' + \
                                str(net.oct3) + '.' + str(net.oct4) + \
                                '/' + str(net.block)
                            if IpEquipamento.objects.filter(ip__networkipv4=net, equipamento__tipo_equipamento=TipoEquipamento.get_tipo_balanceador()).exclude(equipamento=equip).count() == 0:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.' % (net_str, net.vlan.nome))

                        for net in nets_v6_using_balancer_in_vips:
                            net_str = str(net.block1) + ':' + str(net.block2) + ':' + str(net.block3) + ':' + str(net.block4) + ':' + str(
                                net.block5) + ':' + str(net.block6) + ':' + str(net.block7) + ':' + str(net.block8) + '/' + str(net.block)
                            if Ipv6Equipament.objects.filter(ip__networkipv6=net, equipamento__tipo_equipamento=TipoEquipamento.get_tipo_balanceador()).exclude(equipamento=equip).count() == 0:
                                raise EquipTypeCantBeChangedError(
                                    None, 'O tipo de equipamento não pode ser modificado pois este equipamento é o único balanceador disponível na rede %s da vlan %s.' % (net_str, net.vlan.nome))

                ip_equipamento_list = IpEquipamento.objects.filter(
                    equipamento=equip_id)
                ip6_equipamento_list = Ipv6Equipament.objects.filter(
                    equipamento=equip_id)

                # Delete vlan's cache
                key_list = []
                for eq in ip_equipamento_list:
                    vlan = eq.ip.networkipv4.vlan
                    vlan_id = vlan.id
                    key_list.append(vlan_id)

                for eq in ip6_equipamento_list:
                    vlan = eq.ip.networkipv6.vlan
                    vlan_id = vlan.id
                    key_list.append(vlan_id)

                destroy_cache_function(key_list)

                # Delete equipment's cache
                destroy_cache_function([equip_id], True)

                modelo = Modelo.get_by_pk(id_modelo)
                equip.edit(user, nome, tipo_equip, modelo)

                return self.response(dumps_networkapi({}))

        except EquipTypeCantBeChangedError, e:
            return self.response_error(150, e.message)
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to get all Ips (v4) or (v6) of equip on Divisao DC and Ambiente Logico of fisrt Network4 and 6 (if exists) of Environment Vip.

        URL: ip/getbyequipandevip/
        """

        self.log.info('Get Ips by Equip - Evip')
        try:

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

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

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

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

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

            # Valid equip_name
            if not is_valid_string_minsize(
                    equip_name, 3) or not is_valid_string_maxsize(
                        equip_name, 80) or not is_valid_regex(
                            equip_name, '^[A-Z0-9-_]+$'):
                self.log.error(u'Parameter equip_name is invalid. Value: %s',
                               equip_name)
                raise InvalidValueError(None, 'equip_name', equip_name)

            # Business Rules

            # Get Environment VIp
            evip = EnvironmentVip.get_by_pk(id_evip)
            # Get Equipment
            equip = Equipamento.get_by_name(equip_name)

            lista_ips_equip = list()
            lista_ipsv6_equip = list()

            # GET DIVISAO DC AND AMBIENTE_LOGICO OF NET4 AND NET6
            lista_amb_div_4 = list()
            lista_amb_div_6 = list()

            for net in evip.networkipv4_set.select_related('vlan',
                                                           'ambiente').all():

                dict_div_4 = dict()
                dict_div_4['divisao_dc'] = net.vlan.ambiente.divisao_dc_id
                dict_div_4[
                    'ambiente_logico'] = net.vlan.ambiente.ambiente_logico_id

                if dict_div_4 not in lista_amb_div_4:
                    lista_amb_div_4.append(dict_div_4)

            for net in evip.networkipv6_set.select_related('vlan',
                                                           'ambiente').all():

                dict_div_6 = dict()
                dict_div_6['divisao_dc'] = net.vlan.ambiente.divisao_dc_id
                dict_div_6[
                    'ambiente_logico'] = net.vlan.ambiente.ambiente_logico_id
                if dict_div_6 not in lista_amb_div_6:
                    lista_amb_div_6.append(dict_div_6)

            # Get all IPV4's Equipment
            for ipequip in equip.ipequipamento_set.select_related(
                    'ip', 'vlan', 'ambiente').all():
                if ipequip.ip not in lista_ips_equip:
                    for dict_div_amb in lista_amb_div_4:
                        # if ipequip.ip.networkipv4.ambient_vip is not None and
                        # ipequip.ip.networkipv4.ambient_vip.id  == evip.id:
                        if (ipequip.ip.networkipv4.vlan.ambiente.divisao_dc.id
                                == dict_div_amb.get('divisao_dc') and ipequip.
                                ip.networkipv4.vlan.ambiente.ambiente_logico.id
                                == dict_div_amb.get('ambiente_logico')):
                            lista_ips_equip.append(ipequip.ip)

            # Get all IPV6'S Equipment
            for ipequip in equip.ipv6equipament_set.select_related(
                    'ip', 'vlan', 'ambiente').all():
                if ipequip.ip not in lista_ipsv6_equip:
                    for dict_div_amb in lista_amb_div_6:
                        # if ipequip.ip.networkipv6.ambient_vip is not None and
                        # ipequip.ip.networkipv6.ambient_vip.id  == evip.id:
                        print ipequip.ip.networkipv6.vlan.ambiente.divisao_dc.id
                        print dict_div_amb.get('divisao_dc')
                        if (ipequip.ip.networkipv6.vlan.ambiente.divisao_dc.id
                                == dict_div_amb.get('divisao_dc') and ipequip.
                                ip.networkipv6.vlan.ambiente.ambiente_logico.id
                                == dict_div_amb.get('ambiente_logico')):
                            lista_ipsv6_equip.append(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

            if (lista_ip_entregue is None and lista_ip6_entregue is None):
                raise IpNotFoundByEquipAndVipError(
                    None,
                    'Ip não encontrado com equipamento %s e ambiente vip %s' %
                    (equip_name, id_evip))

            return self.response(
                dumps_networkapi({
                    'ipv4': lista_ip_entregue,
                    'ipv6': lista_ip6_entregue
                }))

        except IpNotFoundByEquipAndVipError:
            return self.response_error(317, equip_name, id_evip)
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to get all Ips (v4) or (v6) of equip on Divisao DC and Ambiente Logico of fisrt Network4 and 6 (if exists) of Environment Vip.

        URL: ip/getbyequipandevip/
        '''

        self.log.info('Get Ips by Equip - Evip')
        try:

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

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

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

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

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

            # Valid equip_name
            if not is_valid_string_minsize(equip_name, 3) or not is_valid_string_maxsize(equip_name, 80) or not is_valid_regex(equip_name, "^[A-Z0-9-_]+$"):
                self.log.error(
                    u'Parameter equip_name is invalid. Value: %s', equip_name)
                raise InvalidValueError(None, 'equip_name', equip_name)

            # Business Rules

            # Get Environment VIp
            evip = EnvironmentVip.get_by_pk(id_evip)
            # Get Equipment
            equip = Equipamento.get_by_name(equip_name)

            lista_ips_equip = list()
            lista_ipsv6_equip = list()

            # GET DIVISAO DC AND AMBIENTE_LOGICO OF NET4 AND NET6
            lista_amb_div_4 = list()
            lista_amb_div_6 = list()
            for net in evip.networkipv4_set.select_related().all():

                dict_div_4 = dict()
                dict_div_4['divisao_dc'] = net.vlan.ambiente.divisao_dc_id
                dict_div_4[
                    'ambiente_logico'] = net.vlan.ambiente.ambiente_logico_id

                if dict_div_4 not in lista_amb_div_4:
                    lista_amb_div_4.append(dict_div_4)

            for net in evip.networkipv6_set.select_related().all():

                dict_div_6 = dict()
                dict_div_6['divisao_dc'] = net.vlan.ambiente.divisao_dc_id
                dict_div_6[
                    'ambiente_logico'] = net.vlan.ambiente.ambiente_logico_id
                if dict_div_6 not in lista_amb_div_6:
                    lista_amb_div_6.append(dict_div_6)

            # Get all IPV4's Equipment
            for ipequip in equip.ipequipamento_set.select_related().all():
                if ipequip.ip not in lista_ips_equip:
                    for dict_div_amb in lista_amb_div_4:
                        # if ipequip.ip.networkipv4.ambient_vip is not None and
                        # ipequip.ip.networkipv4.ambient_vip.id  == evip.id:
                        if (ipequip.ip.networkipv4.vlan.ambiente.divisao_dc.id == dict_div_amb.get('divisao_dc') and ipequip.ip.networkipv4.vlan.ambiente.ambiente_logico.id == dict_div_amb.get('ambiente_logico')):
                            lista_ips_equip.append(ipequip.ip)

            # Get all IPV6'S Equipment
            for ipequip in equip.ipv6equipament_set.select_related().all():
                if ipequip.ip not in lista_ipsv6_equip:
                    for dict_div_amb in lista_amb_div_6:
                        # if ipequip.ip.networkipv6.ambient_vip is not None and
                        # ipequip.ip.networkipv6.ambient_vip.id  == evip.id:
                        print ipequip.ip.networkipv6.vlan.ambiente.divisao_dc.id
                        print dict_div_amb.get('divisao_dc')
                        if (ipequip.ip.networkipv6.vlan.ambiente.divisao_dc.id == dict_div_amb.get('divisao_dc') and ipequip.ip.networkipv6.vlan.ambiente.ambiente_logico.id == dict_div_amb.get('ambiente_logico')):
                            lista_ipsv6_equip.append(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

            if (lista_ip_entregue is None and lista_ip6_entregue is None):
                raise IpNotFoundByEquipAndVipError(
                    None, 'Ip não encontrado com equipamento %s e ambiente vip %s' % (equip_name, id_evip))

            return self.response(dumps_networkapi({"ipv4": lista_ip_entregue, "ipv6": lista_ip6_entregue}))

        except IpNotFoundByEquipAndVipError:
            return self.response_error(317, equip_name, id_evip)
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)