def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT change request VIP.

        URLs: /requestvip/<id_vip>/

        deprecated:: Use the new rest API
        """

        self.log.info("Change request VIP")

        try:

            vip_id = kwargs.get('id_vip')

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data, ['real', 'reals_weight', 'reals_priority', 'porta'])

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

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

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

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

            # Valid Ipv4 and Ipv6 ID
            if (vip_map.get('id_ipv4') is None and vip_map.get('id_ipv6') is None):
                self.log.error(
                    u'The id_ipv4 and id_ipv6 parameter is not a valid value: %s.', vip_map.get('id_ipv4'))
                raise InvalidValueError(
                    None, 'id_ipv4 e id_vip6', vip_map.get('id_ipv4'))

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

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

            # Valid Vip validated
            if not is_valid_boolean_param(vip_map.get('validado')):
                self.log.error(
                    u'The validated parameter is not a valid value: %s.', vip_map.get('validado'))
                raise InvalidValueError(
                    None, 'validated', vip_map.get('validado'))

            # Valid Vip vip_created
            if not is_valid_boolean_param(vip_map.get('vip_criado')):
                self.log.error(
                    u'The vip_created parameter is not a valid value: %s.', vip_map.get('vip_criado'))
                raise InvalidValueError(
                    None, 'vip_created', vip_map.get('vip_criado'))

            # Valid maxcon
            if not is_valid_int_greater_equal_zero_param(vip_map.get('maxcon')):
                self.log.error(
                    u'The maxcon parameter is not a valid value: %s.', vip_map.get('maxcon'))
                raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon'))

            # Existing Vip ID
            vip = RequisicaoVips.get_by_pk(vip_id)

            with distributedlock(LOCK_VIP % vip_id):

                # Valid Vip created
                if vip.vip_criado:
                    self.log.error(
                        u'The IP of the request for VIP %d can not be changed because the VIP is already created.' % vip.id)
                    raise RequisicaoVipsAlreadyCreatedError(None)

                # Get variables
                variables_map = vip.variables_to_map()

                # Valid variables
                vip.set_variables(variables_map)

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

                # Valid real names and real ips of real server
                if vip_map.get('reals') is not None:

                    for real in vip_map.get('reals').get('real'):
                        ip_aux_error = real.get('real_ip')
                        equip_aux_error = real.get('real_name')
                        if equip_aux_error is not None:
                            equip = Equipamento.get_by_name(equip_aux_error)
                        else:
                            self.log.error(
                                u'The real_name parameter is not a valid value: None.')
                            raise InvalidValueError(None, 'real_name', 'None')

                        # Valid Real
                        RequisicaoVips.valid_real_server(
                            ip_aux_error, equip, evip, False)

                    # Valid reals_prioritys
                    vip_map, code = vip.valid_values_reals_priority(vip_map)
                    if code is not None:
                        return self.response_error(code)

                    # Valid reals_weight
                    vip_map, code = vip.valid_values_reals_weight(vip_map)
                    if code is not None:
                        return self.response_error(code)

                # Existing IPv4 ID
                if vip_map.get('id_ipv4') is not None:
                    vip.ip = Ip().get_by_pk(vip_map.get('id_ipv4'))
                else:
                    vip.ip = None

                # Existing IPv6 ID
                if vip_map.get('id_ipv6') is not None:
                    vip.ipv6 = Ipv6().get_by_pk(vip_map.get('id_ipv6'))
                else:
                    vip.ipv6 = None

                # Valid ports
                vip_map, code = vip.valid_values_ports(vip_map)
                if code is not None:
                    return self.response_error(code)

                # Valid HealthcheckExpect
                vip_map, vip, code = vip.valid_values_healthcheck(
                    vip_map, vip, evip)
                if code is not None:
                    return self.response_error(code)

                # Existing l7_filter
                if vip_map.get('l7_filter') is not None:
                    vip.l7_filter = vip_map.get('l7_filter')
                else:
                    vip.l7_filter = None

                # If the l7_filter is a rule, set filter_valid to TRUE
                if vip_map.get('rule_id') is not None:
                    # Valid rule
                    if not is_valid_int_greater_zero_param(vip_map.get('rule_id')):
                        self.log.error(
                            u'The rule_id parameter is not a valid value: %s.', vip_map.get('rule_id'))
                        raise InvalidValueError(
                            None, 'rule_id', vip_map.get('rule_id'))

                    rule = Rule.objects.get(pk=vip_map.get('rule_id'))
                    vip.l7_filter = '\n'.join(
                        rule.rulecontent_set.all().values_list('content', flat=True))
                    vip.rule = rule
                else:
                    vip.rule = None

                # set variables
                vip.filter_valid = 1
                vip.validado = 0
                vip.set_variables(vip_map)

                try:
                    # update Resquest Vip
                    vip.save()
                    # update ServerPool, VipPortToPool, ServerPoolMembers
                    vip.save_vips_and_ports(vip_map, user)

                except RequestVipServerPoolConstraintError, e:
                    self.log.error(e.message)
                    return self.response_error(384, e.message)

                except Exception, e:
                    if isinstance(e, IntegrityError):
                        # Duplicate value for Port Vip, Port Real and IP
                        self.log.error(u'Failed to update the request vip.')
                        return self.response_error(353)
                    else:
                        self.log.error(u'Failed to update the request vip.')
                        raise RequisicaoVipsError(
                            e, u'Failed to update the request vip')
    def handle_post(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

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data, ['searchable_columns', 'asorting_cols'])

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

            # Get XML data
            start_record = equipment_map.get('start_record')
            end_record = equipment_map.get('end_record')
            asorting_cols = equipment_map.get('asorting_cols')
            searchable_columns = equipment_map.get('searchable_columns')
            custom_search = equipment_map.get('custom_search')

            name = equipment_map.get('nome')
            iexact = equipment_map.get('exato')
            environment = equipment_map.get('ambiente')
            equip_type = equipment_map.get('tipo_equipamento')
            group = equipment_map.get('grupo')
            ip = equipment_map.get('ip')

            # Business Rules

            # Start with alls
            equip = Equipamento.objects.all()

            if name is not None:
                # If name is valid, add to filter
                if not is_valid_string_minsize(name, 3, False):
                    raise InvalidValueError(None, 'nome', name)
                else:
                    # Iexact must be valid to add name to filter
                    if not is_valid_boolean_param(iexact, False):
                        raise InvalidValueError(None, 'exato', iexact)
                    else:
                        if (iexact is None) or (iexact == 'False') or (iexact == '0'):
                            iexact = False

                        if iexact:
                            equip = equip.filter(nome=name)
                        else:
                            equip = equip.filter(nome__icontains=name)

            # If environment is valid, add to filter
            if environment is not None:
                if not is_valid_int_greater_zero_param(environment, False):
                    raise InvalidValueError(None, 'ambiente', environment)
                else:
                    equip = equip.filter(
                        equipamentoambiente__ambiente__pk=environment)

            if equip_type is not None:
                # If equip_type is valid, add to filter
                if not is_valid_int_greater_zero_param(equip_type, False):
                    raise InvalidValueError(
                        None, 'tipo_equipamento', equip_type)
                else:
                    equip = equip.filter(tipo_equipamento__pk=equip_type)

            if group is not None:
                # If equip_type is valid, add to filter
                if not is_valid_int_greater_zero_param(group, False):
                    raise InvalidValueError(None, 'grupo', group)
                else:
                    equip = equip.filter(grupos__pk=group)

            if ip is not None:
                # If ip is valid
                if not is_valid_string_minsize(ip, 1, False):
                    raise InvalidValueError(None, 'ip', ip)
                else:
                    blocks, ip, version = break_ip(ip)
                    try:
                        IPAddress(ip)
                    except ValueError, e:
                        raise InvalidValueError(None, 'ip', ip)

                    # Filter octs
                    if version == IP_VERSION.IPv4[0]:
                        # IP v4
                        oct1 = oct2 = oct3 = oct4 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ipequipamento__ip__oct1=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ipequipamento__ip__oct2=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ipequipamento__ip__oct3=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ipequipamento__ip__oct4=blocks[3])

                        equip = equip.filter(oct1 & oct2 & oct3 & oct4)
                    else:
                        # IP v6
                        oct1 = oct2 = oct3 = oct4 = oct5 = oct6 = oct7 = oct8 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(
                                ipv6equipament__ip__block1__iexact=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(
                                ipv6equipament__ip__block2__iexact=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(
                                ipv6equipament__ip__block3__iexact=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(
                                ipv6equipament__ip__block4__iexact=blocks[3])
                        if len(blocks[4]) != 0:
                            oct5 = Q(
                                ipv6equipament__ip__block5__iexact=blocks[4])
                        if len(blocks[5]) != 0:
                            oct6 = Q(
                                ipv6equipament__ip__block6__iexact=blocks[5])
                        if len(blocks[6]) != 0:
                            oct7 = Q(
                                ipv6equipament__ip__block7__iexact=blocks[6])
                        if len(blocks[7]) != 0:
                            oct8 = Q(
                                ipv6equipament__ip__block8__iexact=blocks[7])

                        equip = equip.filter(
                            oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8)

            equip = equip.distinct()

            # Datatable paginator
            equip, total = build_query_to_datatable(
                equip, asorting_cols, custom_search, searchable_columns, start_record, end_record)

            itens = get_equips(equip)

            equipment_map = dict()
            equipment_map['equipamento'] = itens
            equipment_map['total'] = total

            return self.response(dumps_networkapi(equipment_map))
Exemple #3
0
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all VLANs by search parameters.

        URLs: /vlan/find/
        """

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

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT,
                            AdminPermission.READ_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,
                                       ['searchable_columns', 'asorting_cols'])

            # 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
            start_record = vlan_map.get('start_record')
            end_record = vlan_map.get('end_record')
            asorting_cols = vlan_map.get('asorting_cols')
            searchable_columns = vlan_map.get('searchable_columns')
            custom_search = vlan_map.get('custom_search')

            number = vlan_map.get('numero')
            name = vlan_map.get('nome')
            iexact = vlan_map.get('exato')
            environment = vlan_map.get('ambiente')
            net_type = vlan_map.get('tipo_rede')
            network = vlan_map.get('rede')
            ip_version = vlan_map.get('versao')
            subnet = vlan_map.get('subrede')
            acl = vlan_map.get('acl')

            # Business Rules

            # Start with alls
            vlans = Vlan.objects.all().prefetch_related(
                'networkipv4_set', 'networkipv6_set')

            if number is not None:
                # If number is valid, add to filter
                if not is_valid_int_greater_zero_param(number, False):
                    raise InvalidValueError(None, 'numero', number)
                else:
                    vlans = vlans.filter(num_vlan=number)

            if name is not None:
                # If name is valid, add to filter
                if not is_valid_string_minsize(name, 3, False):
                    raise InvalidValueError(None, 'nome', name)
                else:
                    # Iexact must be valid to add name to filter
                    if not is_valid_boolean_param(iexact, False):
                        raise InvalidValueError(None, 'exato', iexact)
                    else:
                        if (iexact is None) or (iexact == 'False') or (iexact
                                                                       == '0'):
                            iexact = False

                        if iexact:
                            vlans = vlans.filter(nome=name)
                        else:
                            vlans = vlans.filter(nome__icontains=name)

            # If environment is valid, add to filter
            if environment is not None:
                if not is_valid_int_greater_zero_param(environment, False):
                    raise InvalidValueError(None, 'ambiente', environment)
                else:
                    vlans = vlans.filter(ambiente__pk=environment)

            if net_type is not None:
                # If net_type is valid, add to filter
                if not is_valid_int_greater_zero_param(net_type, False):
                    raise InvalidValueError(None, 'tipo_rede', net_type)
                else:
                    q1 = Q(networkipv4__network_type__id=net_type)
                    q2 = Q(networkipv6__network_type__id=net_type)
                    vlans = vlans.filter(q1 | q2)

            if acl is not None:
                # If acl is valid, add to filter
                if not is_valid_boolean_param(acl, False):
                    raise InvalidValueError(None, 'acl', acl)
                else:
                    if (acl is None) or (acl == 'False') or (acl == '0'):
                        acl = False
                    # If acl is true, only show vlans with false acl_valida
                    if acl:
                        vlans = vlans.filter(acl_valida=False)

            # If ip_version is valid
            if not is_valid_int_greater_equal_zero_param(ip_version):
                raise InvalidValueError(None, 'versao', ip_version)
            else:
                if ip_version == '0':
                    vlans = vlans.filter(
                        Q(networkipv6__isnull=True)
                        | Q(networkipv4__isnull=False))
                elif ip_version == '1':
                    vlans = vlans.filter(
                        Q(networkipv4__isnull=True)
                        | Q(networkipv6__isnull=False))

            if network is not None:
                # If network is valid
                if not is_valid_string_minsize(network, 1, False):
                    raise InvalidValueError(None, 'rede', network)
                else:
                    blocks, network, version = break_network(network)
                    try:
                        network_ip = IPNetwork(network)
                    except ValueError, e:
                        raise InvalidValueError(None, 'rede', network)

                # If subnet is valid, add to filter
                if not (subnet == '0' or subnet == '1'):
                    raise InvalidValueError(None, 'subrede', subnet)
                else:
                    # If subnet is 0, only filter network octs
                    if subnet == '0':

                        # Filter octs
                        if version == IP_VERSION.IPv4[0]:
                            # Network IP v4
                            oct1 = Q()
                            oct2 = Q()
                            oct3 = Q()
                            oct4 = Q()
                            blk = Q()

                            if len(blocks[0]) != 0:
                                oct1 = Q(networkipv4__oct1=blocks[0])
                            if len(blocks[1]) != 0:
                                oct2 = Q(networkipv4__oct2=blocks[1])
                            if len(blocks[2]) != 0:
                                oct3 = Q(networkipv4__oct3=blocks[2])
                            if len(blocks[3]) != 0:
                                oct4 = Q(networkipv4__oct4=blocks[3])
                            if len(blocks[4]) != 0:
                                blk = Q(networkipv4__block=blocks[4])

                            vlans = vlans.filter(oct1 & oct2 & oct3 & oct4
                                                 & blk)
                        else:
                            # Network IP v6
                            oct1 = Q()
                            oct2 = Q()
                            oct3 = Q()
                            oct4 = Q()
                            oct5 = Q()
                            oct6 = Q()
                            oct7 = Q()
                            oct8 = Q()
                            blk = Q()

                            if len(blocks[0]) != 0:
                                oct1 = Q(networkipv6__block1__iexact=blocks[0])
                            if len(blocks[1]) != 0:
                                oct2 = Q(networkipv6__block2__iexact=blocks[1])
                            if len(blocks[2]) != 0:
                                oct3 = Q(networkipv6__block3__iexact=blocks[2])
                            if len(blocks[3]) != 0:
                                oct4 = Q(networkipv6__block4__iexact=blocks[3])
                            if len(blocks[4]) != 0:
                                oct5 = Q(networkipv6__block5__iexact=blocks[4])
                            if len(blocks[5]) != 0:
                                oct6 = Q(networkipv6__block6__iexact=blocks[5])
                            if len(blocks[6]) != 0:
                                oct7 = Q(networkipv6__block7__iexact=blocks[6])
                            if len(blocks[7]) != 0:
                                oct8 = Q(networkipv6__block8__iexact=blocks[7])
                            if len(blocks[8]) != 0:
                                blk = Q(networkipv6__block=blocks[8])

                            vlans = vlans.filter(oct1 & oct2 & oct3 & oct4
                                                 & oct5 & oct6 & oct7 & oct8
                                                 & blk)
                    # If subnet is 1
                    else:

                        if version == IP_VERSION.IPv4[0]:
                            expl = split(network_ip.network.exploded, '.')
                        else:
                            expl = split(network_ip.network.exploded, ':')

                        expl.append(str(network_ip.prefixlen))

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

                        # First, get all vlans filtered until now
                        itens = get_networks_simple(vlans)

                        ids_exclude = []
                        # Then iterate over it to verify each vlan
                        for vlan in itens:

                            is_subnet = verify_subnet(vlan, network_ip,
                                                      version)
                            if not is_subnet:
                                ids_exclude.append(vlan['id'])

                        vlans = vlans.exclude(id__in=ids_exclude)

            # Custom order
            if asorting_cols:
                if 'ambiente' in asorting_cols:
                    vlans = vlans.order_by('ambiente__divisao_dc__nome',
                                           'ambiente__ambiente_logico__nome',
                                           'ambiente__grupo_l3__nome')
                    asorting_cols.remove('ambiente')
                if '-ambiente' in asorting_cols:
                    vlans = vlans.order_by('-ambiente__divisao_dc__nome',
                                           '-ambiente__ambiente_logico__nome',
                                           '-ambiente__grupo_l3__nome')
                    asorting_cols.remove('-ambiente')
                if 'tipo_rede' in asorting_cols:
                    vlans = vlans.order_by(
                        'networkipv4__network_type__tipo_rede',
                        'networkipv6__network_type__tipo_rede')
                    asorting_cols.remove('tipo_rede')
                if '-tipo_rede' in asorting_cols:
                    vlans = vlans.order_by(
                        '-networkipv4__network_type__tipo_rede',
                        '-networkipv6__network_type__tipo_rede')
                    asorting_cols.remove('-tipo_rede')
                if 'network' in asorting_cols:
                    vlans = vlans.order_by(
                        'networkipv4__oct1', 'networkipv4__oct2',
                        'networkipv4__oct3', 'networkipv4__oct4',
                        'networkipv4__block', 'networkipv6__block1',
                        'networkipv6__block2', 'networkipv6__block3',
                        'networkipv6__block4', 'networkipv6__block5',
                        'networkipv6__block6', 'networkipv6__block7',
                        'networkipv6__block8', 'networkipv6__block')
                    asorting_cols.remove('network')
                if '-network' in asorting_cols:
                    vlans = vlans.order_by(
                        '-networkipv4__oct1', '-networkipv4__oct2',
                        '-networkipv4__oct3', '-networkipv4__oct4',
                        '-networkipv4__block', '-networkipv6__block1',
                        '-networkipv6__block2', '-networkipv6__block3',
                        '-networkipv6__block4', '-networkipv6__block5',
                        '-networkipv6__block6', '-networkipv6__block7',
                        '-networkipv6__block8', '-networkipv6__block')
                    asorting_cols.remove('-network')

            vlans = vlans.distinct()

            # Datatable paginator
            vlans, total = build_query_to_datatable(vlans, asorting_cols,
                                                    custom_search,
                                                    searchable_columns,
                                                    start_record, end_record)
            vlans = vlans.prefetch_related(
                'ambiente', 'networkipv4_set__network_type',
                'networkipv4_set__ip_set__ipequipamento_set__equipamento__equipamentoambiente_set__ambiente',
                'networkipv6_set__network_type',
                'networkipv6_set__ipv6_set__ipv6equipament_set__equipamento__equipamentoambiente_set__ambiente'
            )

            itens = get_networks(vlans, False)

            vlan_map = dict()
            vlan_map['vlan'] = itens
            vlan_map['total'] = total

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

        URL: user/<id_user>/
        """
        try:

            self.log.info('Edit User')

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

            id_user = kwargs.get('id_user')

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

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

            # Get XML data
            username = user_map.get('user')
            password = user_map.get('password')
            name = user_map.get('name')
            email = user_map.get('email')
            active = user_map.get('active')
            user_ldap = user_map.get('user_ldap')

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

            # Valid username
            if not is_valid_string_minsize(
                    username, 3) or not is_valid_string_maxsize(username, 45):
                self.log.error(u'Parameter user is invalid. Value: %s',
                               username)
                raise InvalidValueError(None, 'user', username)

            # Valid pwd
            if not is_valid_string_minsize(
                    password, 3) or not is_valid_string_maxsize(password, 45):
                self.log.error(u'Parameter password is invalid. Value: ****')
                raise InvalidValueError(None, 'password', '****')

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

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

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

            # Valid LDAP username
            if not is_valid_string_minsize(
                    user_ldap, 3, False) or not is_valid_string_maxsize(
                        user_ldap, 45, False):
                self.log.error(u'Parameter user_ldap is invalid. Value: %s',
                               user_ldap)
                raise InvalidValueError(None, 'user_ldap', user_ldap)

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            with distributedlock(LOCK_USER % id_user):

                try:
                    if usr.user.lower() != username.lower():
                        Usuario.get_by_user(username)
                        raise UsuarioNameDuplicatedError(
                            None,
                            u'Já existe um usuário com o valor user %s.' %
                            username)
                except UsuarioNotFoundError:
                    pass

                # set variables
                usr.user = username
                usr.pwd = password
                usr.nome = name
                usr.email = email
                usr.ativo = convert_string_or_int_to_boolean(active)
                usr.user_ldap = user_ldap

                try:
                    # update User
                    usr.save()
                except Exception, e:
                    self.log.error(u'Failed to update the user.')
                    raise UsuarioError(e, u'Failed to update the user.')

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

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data, ["searchable_columns", "asorting_cols"])

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

            # Get XML data
            start_record = equipment_map.get("start_record")
            end_record = equipment_map.get("end_record")
            asorting_cols = equipment_map.get("asorting_cols")
            searchable_columns = equipment_map.get("searchable_columns")
            custom_search = equipment_map.get("custom_search")

            name = equipment_map.get("nome")
            iexact = equipment_map.get("exato")
            environment = equipment_map.get("ambiente")
            equip_type = equipment_map.get("tipo_equipamento")
            group = equipment_map.get("grupo")
            ip = equipment_map.get("ip")

            # Business Rules

            # Start with alls
            equip = Equipamento.objects.select_related().all()

            if name is not None:
                # If name is valid, add to filter
                if not is_valid_string_minsize(name, 3, False):
                    raise InvalidValueError(None, 'nome', name)
                else:
                    # Iexact must be valid to add name to filter
                    if not is_valid_boolean_param(iexact, False):
                        raise InvalidValueError(None, 'exato', iexact)
                    else:
                        if (iexact is None) or (iexact == "False") or (iexact == "0"):
                            iexact = False

                        if iexact:
                            equip = equip.filter(nome=name)
                        else:
                            equip = equip.filter(nome__icontains=name)

            # If environment is valid, add to filter
            if environment is not None:
                if not is_valid_int_greater_zero_param(environment, False):
                    raise InvalidValueError(None, 'ambiente', environment)
                else:
                    equip = equip.filter(
                        equipamentoambiente__ambiente__pk=environment)

            if equip_type is not None:
                # If equip_type is valid, add to filter
                if not is_valid_int_greater_zero_param(equip_type, False):
                    raise InvalidValueError(
                        None, 'tipo_equipamento', equip_type)
                else:
                    equip = equip.filter(tipo_equipamento__pk=equip_type)

            if group is not None:
                # If equip_type is valid, add to filter
                if not is_valid_int_greater_zero_param(group, False):
                    raise InvalidValueError(None, 'grupo', group)
                else:
                    equip = equip.filter(grupos__pk=group)

            if ip is not None:
                # If ip is valid
                if not is_valid_string_minsize(ip, 1, False):
                    raise InvalidValueError(None, 'ip', ip)
                else:
                    blocks, ip, version = break_ip(ip)
                    try:
                        IPAddress(ip)
                    except ValueError, e:
                        raise InvalidValueError(None, 'ip', ip)

                    # Filter octs
                    if version == IP_VERSION.IPv4[0]:
                        # IP v4
                        oct1 = oct2 = oct3 = oct4 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ipequipamento__ip__oct1=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ipequipamento__ip__oct2=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ipequipamento__ip__oct3=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ipequipamento__ip__oct4=blocks[3])

                        equip = equip.filter(oct1 & oct2 & oct3 & oct4)
                    else:
                        # IP v6
                        oct1 = oct2 = oct3 = oct4 = oct5 = oct6 = oct7 = oct8 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(
                                ipv6equipament__ip__block1__iexact=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(
                                ipv6equipament__ip__block2__iexact=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(
                                ipv6equipament__ip__block3__iexact=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(
                                ipv6equipament__ip__block4__iexact=blocks[3])
                        if len(blocks[4]) != 0:
                            oct5 = Q(
                                ipv6equipament__ip__block5__iexact=blocks[4])
                        if len(blocks[5]) != 0:
                            oct6 = Q(
                                ipv6equipament__ip__block6__iexact=blocks[5])
                        if len(blocks[6]) != 0:
                            oct7 = Q(
                                ipv6equipament__ip__block7__iexact=blocks[6])
                        if len(blocks[7]) != 0:
                            oct8 = Q(
                                ipv6equipament__ip__block8__iexact=blocks[7])

                        equip = equip.filter(
                            oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8)

            equip = equip.distinct()

            # Datatable paginator
            equip, total = build_query_to_datatable(
                equip, asorting_cols, custom_search, searchable_columns, start_record, end_record)

            itens = get_equips(equip)

            equipment_map = dict()
            equipment_map["equipamento"] = itens
            equipment_map["total"] = total

            return self.response(dumps_networkapi(equipment_map))
    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para criar uma nova interface para o equipamento

        URL: /interface/ 

        """
        # Obtém dados do request e verifica acesso
        try:

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

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

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

            # Valid id_equipamento value
            id_equipamento = interface_map.get('id_equipamento')
            if not is_valid_int_greater_zero_param(id_equipamento):
                self.log.error(
                    u'Parameter id_equipamento is invalid. Value: %s', id_equipamento)
                raise InvalidValueError(None, 'id_equipamento', id_equipamento)
            else:
                id_equipamento = int(id_equipamento)

            # Check existence
            Equipamento.get_by_pk(id_equipamento)

            # Verify permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION, None,
                            id_equipamento, AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            # Valid name value
            nome = interface_map.get('nome')
            if not is_valid_string_minsize(nome, 1) or not is_valid_string_maxsize(nome, 20):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)

            # Valid protegida value
            protegida = interface_map.get('protegida')
            if not is_valid_boolean_param(protegida):
                self.log.error(
                    u'Parameter protegida is invalid. Value: %s', protegida)
                raise InvalidValueError(None, 'protegida', protegida)
            else:
                protegida = convert_string_or_int_to_boolean(protegida)

            # Valid descricao value
            descricao = interface_map.get('descricao')
            if descricao is not None:
                if not is_valid_string_minsize(descricao, 3) or not is_valid_string_maxsize(descricao, 200):
                    self.log.error(
                        u'Parameter descricao is invalid. Value: %s', descricao)
                    raise InvalidValueError(None, 'descricao', descricao)

            # Valid "id_ligacao_front" value
            id_ligacao_front = interface_map.get('id_ligacao_front')
            if id_ligacao_front is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_front):
                    self.log.error(
                        u'The id_ligacao_front parameter is not a valid value: %s.', id_ligacao_front)
                    raise InvalidValueError(
                        None, 'id_ligacao_front', id_ligacao_front)
                else:
                    id_ligacao_front = int(id_ligacao_front)
                    ligacao_front = Interface(id=id_ligacao_front)
            else:
                ligacao_front = None

            # Valid "id_ligacao_back" value
            id_ligacao_back = interface_map.get('id_ligacao_back')
            if id_ligacao_back is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_back):
                    self.log.error(
                        u'The id_ligacao_back parameter is not a valid value: %s.', id_ligacao_back)
                    raise InvalidValueError(
                        None, 'id_ligacao_back', id_ligacao_back)
                else:
                    id_ligacao_back = int(id_ligacao_back)
                    ligacao_back = Interface(id=id_ligacao_back)
            else:
                ligacao_back = None

            tipo_interface = interface_map.get('tipo')
            if tipo_interface == None:
                tipo_interface = "Access"
            tipo_interface = TipoInterface.get_by_name(tipo_interface)

            vlan = interface_map.get('vlan')

            # Cria a interface conforme dados recebidos no XML
            interface = Interface(
                interface=nome,
                protegida=protegida,
                descricao=descricao,
                ligacao_front=ligacao_front,
                ligacao_back=ligacao_back,
                equipamento=Equipamento(id=id_equipamento),
                tipo=tipo_interface,
                vlan_nativa=vlan
            )

            interface.create(user)

            networkapi_map = dict()
            interface_map = dict()

            interface_map['id'] = interface.id
            networkapi_map['interface'] = interface_map

            return self.response(dumps_networkapi(networkapi_map))

        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):
        """Treat requests POST to add Administrative Permission.

        URL: aperms/
        """

        try:

            self.log.info('Add Administrative Permission')

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

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

            # Get XML data
            id_permission = perm_map.get('id_permission')
            id_group = perm_map.get('id_group')
            read = perm_map.get('read')
            write = perm_map.get('write')

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

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

            # Valid Read
            if not is_valid_boolean_param(read):
                self.log.error(
                    u'The read parameter is not a valid value: %s.', read)
                raise InvalidValueError(None, 'read', read)

            # Valid Read
            if not is_valid_boolean_param(write):
                self.log.error(
                    u'The write parameter is not a valid value: %s.', write)
                raise InvalidValueError(None, 'write', write)

            # Find Permission by ID to check if it exist
            permission = Permission.get_by_pk(id_permission)

            # Find UGroup by ID to check if it exist
            ugroup = UGrupo.get_by_pk(id_group)

            try:
                PermissaoAdministrativa.get_permission_by_permission_ugroup(
                    id_permission, id_group)
                raise PermissaoAdministrativaDuplicatedError(
                    None, permission.function)
            except PermissaoAdministrativaNotFoundError:
                pass

            adm_perm = PermissaoAdministrativa()

            # set variables
            adm_perm.permission = permission
            adm_perm.ugrupo = ugroup
            adm_perm.leitura = convert_string_or_int_to_boolean(read)
            adm_perm.escrita = convert_string_or_int_to_boolean(write)

            try:
                # save Administrative Permission
                adm_perm.save()
            except Exception, e:
                self.log.error(
                    u'Failed to save the administrative permission.')
                raise GrupoError(
                    e, u'Failed to save the administrative permission.')

            perm_map = dict()
            perm_map['perm'] = model_to_dict(
                adm_perm, exclude=['permission', 'leitura', 'escrita', 'ugrupo'])

            return self.response(dumps_networkapi(perm_map))
Exemple #9
0
def insert_equipment(equipment_map, user):
    """
    Insere um equipamento e o relacionamento entre equipamento e o grupo.

    @param equipment_map: Map com as chaves: id_grupo, id_tipo_equipamento, id_modelo e nome
    @param user: Usuário autenticado na API.

    @return Em caso de erro retorna a tupla: (código da mensagem de erro, argumento01, argumento02, ...)
            Em caso de sucesso retorna a tupla: (0, <identificador do equipamento_grupo>, <equipamento>)

    @raise InvalidGroupToEquipmentTypeError: Equipamento do grupo “Equipamentos Orquestração” somente poderá ser criado com tipo igual a “Servidor Virtual”.

    @raise EGrupoNotFoundError: Grupo não cadastrado.

    @raise GrupoError: Falha ao pesquisar o Grupo.

    @raise TipoEquipamentoNotFoundError: Tipo de equipamento nao cadastrado.

    @raise ModeloNotFoundError: Modelo nao cadastrado.

    @raise EquipamentoNameDuplicatedError: Nome do equipamento duplicado.

    @raise EquipamentoError: Falha ou inserir o equipamento.

    @raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.

    """
    log = logging.getLogger('insert_equipment')

    log.debug('EQUIPAMENTO_MAP: %s', equipment_map)

    equipment = Equipamento()
    equipment.tipo_equipamento = TipoEquipamento()
    equipment.modelo = Modelo()

    group_id = equipment_map.get('id_grupo')
    if not is_valid_int_greater_zero_param(group_id):
        log.error(u'The group_id parameter is not a valid value: %s.',
                  group_id)
        raise InvalidValueError(None, 'group_id', group_id)
    else:
        group_id = int(group_id)

    if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                    AdminPermission.WRITE_OPERATION, group_id, None,
                    AdminPermission.EQUIP_WRITE_OPERATION):
        raise UserNotAuthorizedError(
            None, u'Usuário não tem permissão para executar a operação.')

    equipment_type_id = equipment_map.get('id_tipo_equipamento')
    if not is_valid_int_greater_zero_param(equipment_type_id):
        log.error(u'The equipment_type_id parameter is not a valid value: %s.',
                  equipment_type_id)
        raise InvalidValueError(None, 'equipment_type_id', equipment_type_id)
    else:
        equipment.tipo_equipamento.id = int(equipment_type_id)

    model_id = equipment_map.get('id_modelo')
    if not is_valid_int_greater_zero_param(model_id):
        log.error(u'The model_id parameter is not a valid value: %s.',
                  model_id)
        raise InvalidValueError(None, 'model_id', model_id)
    else:
        equipment.modelo.id = int(model_id)

    name = equipment_map.get('nome')
    if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(
            name, 50):
        log.error(u'The name parameter is not a valid value: %s.', name)
        raise InvalidValueError(None, 'name', name)
    else:
        equipment.nome = name

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

    equipment_group_id = equipment.create(user, group_id)

    return 0, equipment_group_id, equipment
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all Vip Requests by search parameters.

        URLs: /requestvip/get_by_ip_id/
        """

        self.log.info("Find all Vip Requests")

        try:

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

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data, ["searchable_columns", "asorting_cols"])

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

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

            # Get XML data
            start_record = vip_map.get("start_record")
            end_record = vip_map.get("end_record")
            asorting_cols = vip_map.get("asorting_cols")
            searchable_columns = vip_map.get("searchable_columns")
            custom_search = vip_map.get("custom_search")

            id_vip = vip_map.get("id_vip")
            ip = vip_map.get("ip")
            created_vip = vip_map.get("create")
            if created_vip == "True":
                create = True
            elif created_vip == "False":
                create = None
            else:
                create = created_vip

            # Business Rules

            # Start with all

            vip = RequisicaoVips.objects.all()

            if id_vip is not None and ip is not None:
                raise InvalidValueError(None, "id_vip - ip", "%s - %s" % (id_vip, ip))

            if id_vip is not None:
                # If id_vip is valid, add to filter
                if not is_valid_int_greater_zero_param(id_vip, False):
                    raise InvalidValueError(None, "id_vip", id_vip)
                else:
                    vip = vip.filter(id=id_vip)

            if create is not None:
                # if create is valid, add to filter
                if not is_valid_boolean_param(create, False):
                    raise InvalidValueError(None, "vip_criado", create)
                else:
                    vip = vip.filter(vip_criado=create)

            if ip is not None:
                # If ip is valid
                if not is_valid_string_minsize(ip, 1, False):
                    raise InvalidValueError(None, "ip", ip)
                else:
                    blocks, ip, version = break_ip(ip)
                    try:
                        IPAddress(ip)
                    except ValueError, e:
                        raise InvalidValueError(None, "ip", ip)

                    # Filter octs
                    if version == IP_VERSION.IPv4[0]:
                        # IP v4
                        oct1 = oct2 = oct3 = oct4 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ip__oct1=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ip__oct2=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ip__oct3=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ip__oct4=blocks[3])

                        vip = vip.filter(oct1 & oct2 & oct3 & oct4)
                    else:
                        # IP v6
                        oct1 = oct2 = oct3 = oct4 = oct5 = oct6 = oct7 = oct8 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ipv6__block1__iexact=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ipv6__block2__iexact=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ipv6__block3__iexact=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ipv6__block4__iexact=blocks[3])
                        if len(blocks[4]) != 0:
                            oct5 = Q(ipv6__block5__iexact=blocks[4])
                        if len(blocks[5]) != 0:
                            oct6 = Q(ipv6__block6__iexact=blocks[5])
                        if len(blocks[6]) != 0:
                            oct7 = Q(ipv6__block7__iexact=blocks[6])
                        if len(blocks[7]) != 0:
                            oct8 = Q(ipv6__block8__iexact=blocks[7])

                        vip = vip.filter(oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8)

            vip = vip.distinct()

            vip = vip.order_by("-pk")

            # Datatable paginator
            vip, total = build_query_to_datatable(
                vip, asorting_cols, custom_search, searchable_columns, start_record, end_record
            )

            itens = get_vips(vip)

            vip_map = dict()
            vip_map["vips"] = itens
            vip_map["total"] = total

            return self.response(dumps_networkapi(vip_map))
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit Administrative Permission.

        URL: perms/<id_perm>/
        """
        try:

            self.log.info("Edit Administrative Permission")

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

            id_perm = kwargs.get('id_perm')

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

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

            # Get XML data
            id_permission = perm_map.get('id_permission')
            id_group = perm_map.get('id_group')
            read = perm_map.get('read')
            write = perm_map.get('write')

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

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

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

            # Valid Read
            if not is_valid_boolean_param(read):
                self.log.error(
                    u'The read parameter is not a valid value: %s.', read)
                raise InvalidValueError(None, 'read', read)

            # Valid Read
            if not is_valid_boolean_param(write):
                self.log.error(
                    u'The write parameter is not a valid value: %s.', write)
                raise InvalidValueError(None, 'write', write)

            # Find Permission by ID to check if it exist
            adm_perm = PermissaoAdministrativa.get_by_pk(id_perm)

            with distributedlock(LOCK_PERM % id_perm):

                # Find Permission by ID to check if it exist
                permission = Permission.get_by_pk(id_permission)

                # Find UGroup by ID to check if it exist
                ugroup = UGrupo.get_by_pk(id_group)

                try:
                    perm = PermissaoAdministrativa.get_permission_by_permission_ugroup(
                        id_permission, id_group)
                    if perm.id != int(id_perm):
                        raise PermissaoAdministrativaDuplicatedError(
                            None, permission.function)
                except PermissaoAdministrativaNotFoundError:
                    pass

                # set variables
                adm_perm.permission = permission
                adm_perm.ugrupo = ugroup
                adm_perm.leitura = convert_string_or_int_to_boolean(read)
                adm_perm.escrita = convert_string_or_int_to_boolean(write)

                try:
                    # update Administrative Permission
                    adm_perm.save()
                except Exception, e:
                    self.log.error(
                        u'Failed to update the administrative permission.')
                    raise PermissionError(
                        e, u'Failed to update the administrative permission.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Exemple #12
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT change request VIP.

        URLs: /requestvip/<id_vip>/

        deprecated:: Use the new rest API
        """

        self.log.info('Change request VIP')

        try:

            vip_id = kwargs.get('id_vip')

            # Load XML data
            xml_map, attrs_map = loads(
                request.raw_post_data,
                ['real', 'reals_weight', 'reals_priority', 'porta'])

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

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

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

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

            # Valid Ipv4 and Ipv6 ID
            if (vip_map.get('id_ipv4') is None
                    and vip_map.get('id_ipv6') is None):
                self.log.error(
                    u'The id_ipv4 and id_ipv6 parameter is not a valid value: %s.',
                    vip_map.get('id_ipv4'))
                raise InvalidValueError(None, 'id_ipv4 e id_vip6',
                                        vip_map.get('id_ipv4'))

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

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

            # Valid Vip validated
            if not is_valid_boolean_param(vip_map.get('validado')):
                self.log.error(
                    u'The validated parameter is not a valid value: %s.',
                    vip_map.get('validado'))
                raise InvalidValueError(None, 'validated',
                                        vip_map.get('validado'))

            # Valid Vip vip_created
            if not is_valid_boolean_param(vip_map.get('vip_criado')):
                self.log.error(
                    u'The vip_created parameter is not a valid value: %s.',
                    vip_map.get('vip_criado'))
                raise InvalidValueError(None, 'vip_created',
                                        vip_map.get('vip_criado'))

            # Valid maxcon
            if not is_valid_int_greater_equal_zero_param(
                    vip_map.get('maxcon')):
                self.log.error(
                    u'The maxcon parameter is not a valid value: %s.',
                    vip_map.get('maxcon'))
                raise InvalidValueError(None, 'maxcon', vip_map.get('maxcon'))

            # Existing Vip ID
            vip = RequisicaoVips.get_by_pk(vip_id)

            with distributedlock(LOCK_VIP % vip_id):

                # Valid Vip created
                if vip.vip_criado:
                    self.log.error(
                        u'The IP of the request for VIP %d can not be changed because the VIP is already created.'
                        % vip.id)
                    raise RequisicaoVipsAlreadyCreatedError(None)

                # Get variables
                variables_map = vip.variables_to_map()

                # Valid variables
                vip.set_variables(variables_map)

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

                # Valid real names and real ips of real server
                if vip_map.get('reals') is not None:

                    for real in vip_map.get('reals').get('real'):
                        ip_aux_error = real.get('real_ip')
                        equip_aux_error = real.get('real_name')
                        if equip_aux_error is not None:
                            equip = Equipamento.get_by_name(equip_aux_error)
                        else:
                            self.log.error(
                                u'The real_name parameter is not a valid value: None.'
                            )
                            raise InvalidValueError(None, 'real_name', 'None')

                        # Valid Real
                        RequisicaoVips.valid_real_server(
                            ip_aux_error, equip, evip, False)

                    # Valid reals_prioritys
                    vip_map, code = vip.valid_values_reals_priority(vip_map)
                    if code is not None:
                        return self.response_error(code)

                    # Valid reals_weight
                    vip_map, code = vip.valid_values_reals_weight(vip_map)
                    if code is not None:
                        return self.response_error(code)

                # Existing IPv4 ID
                if vip_map.get('id_ipv4') is not None:
                    vip.ip = Ip().get_by_pk(vip_map.get('id_ipv4'))
                else:
                    vip.ip = None

                # Existing IPv6 ID
                if vip_map.get('id_ipv6') is not None:
                    vip.ipv6 = Ipv6().get_by_pk(vip_map.get('id_ipv6'))
                else:
                    vip.ipv6 = None

                # Valid ports
                vip_map, code = vip.valid_values_ports(vip_map)
                if code is not None:
                    return self.response_error(code)

                # Valid HealthcheckExpect
                vip_map, vip, code = vip.valid_values_healthcheck(
                    vip_map, vip, evip)
                if code is not None:
                    return self.response_error(code)

                # Existing l7_filter
                if vip_map.get('l7_filter') is not None:
                    vip.l7_filter = vip_map.get('l7_filter')
                else:
                    vip.l7_filter = None

                # If the l7_filter is a rule, set filter_valid to TRUE
                if vip_map.get('rule_id') is not None:
                    # Valid rule
                    if not is_valid_int_greater_zero_param(
                            vip_map.get('rule_id')):
                        self.log.error(
                            u'The rule_id parameter is not a valid value: %s.',
                            vip_map.get('rule_id'))
                        raise InvalidValueError(None, 'rule_id',
                                                vip_map.get('rule_id'))

                    rule = Rule.objects.get(pk=vip_map.get('rule_id'))
                    vip.l7_filter = '\n'.join(
                        rule.rulecontent_set.all().values_list('content',
                                                               flat=True))
                    vip.rule = rule
                else:
                    vip.rule = None

                # set variables
                vip.filter_valid = 1
                vip.validado = 0
                vip.set_variables(vip_map)

                try:
                    # update Resquest Vip
                    vip.save()
                    # update ServerPool, VipPortToPool, ServerPoolMembers
                    vip.save_vips_and_ports(vip_map, user)

                    # SYNC_VIP
                    old_to_new(vip)

                except RequestVipServerPoolConstraintError, e:
                    self.log.error(e.message)
                    return self.response_error(384, e.message)

                except Exception, e:
                    if isinstance(e, IntegrityError):
                        # Duplicate value for Port Vip, Port Real and IP
                        self.log.error(u'Failed to update the request vip.')
                        return self.response_error(353)
                    else:
                        self.log.error(u'Failed to update the request vip.')
                        raise RequisicaoVipsError(
                            e, u'Failed to update the request vip')
    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to find all Vip Requests by search parameters.

        URLs: /requestvip/get_by_ip_id/
        """

        self.log.info('Find all Vip Requests')

        try:

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

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data,
                                       ["searchable_columns", "asorting_cols"])

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

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

            # Get XML data
            start_record = vip_map.get("start_record")
            end_record = vip_map.get("end_record")
            asorting_cols = vip_map.get("asorting_cols")
            searchable_columns = vip_map.get("searchable_columns")
            custom_search = vip_map.get("custom_search")

            id_vip = vip_map.get("id_vip")
            ip = vip_map.get("ip")
            created_vip = vip_map.get("create")
            if created_vip == 'True':
                create = True
            elif created_vip == 'False':
                create = None
            else:
                create = created_vip

            # Business Rules

            # Start with all

            vip = RequisicaoVips.objects.all()

            if id_vip is not None and ip is not None:
                raise InvalidValueError(None, 'id_vip - ip',
                                        "%s - %s" % (id_vip, ip))

            if id_vip is not None:
                # If id_vip is valid, add to filter
                if not is_valid_int_greater_zero_param(id_vip, False):
                    raise InvalidValueError(None, 'id_vip', id_vip)
                else:
                    vip = vip.filter(id=id_vip)

            if create is not None:
                # if create is valid, add to filter
                if not is_valid_boolean_param(create, False):
                    raise InvalidValueError(None, 'vip_criado', create)
                else:
                    vip = vip.filter(vip_criado=create)

            if ip is not None:
                # If ip is valid
                if not is_valid_string_minsize(ip, 1, False):
                    raise InvalidValueError(None, 'ip', ip)
                else:
                    blocks, ip, version = break_ip(ip)
                    try:
                        IPAddress(ip)
                    except ValueError, e:
                        raise InvalidValueError(None, 'ip', ip)

                    # Filter octs
                    if version == IP_VERSION.IPv4[0]:
                        # IP v4
                        oct1 = oct2 = oct3 = oct4 = Q()

                        if len(blocks[0]) != 0:
                            oct1 = Q(ip__oct1=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ip__oct2=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ip__oct3=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ip__oct4=blocks[3])

                        vip = vip.filter(oct1 & oct2 & oct3 & oct4)
                    else:
                        # IP v6
                        oct1 = oct2 = oct3 = oct4 = oct5 = oct6 = oct7 = oct8 = Q(
                        )

                        if len(blocks[0]) != 0:
                            oct1 = Q(ipv6__block1__iexact=blocks[0])
                        if len(blocks[1]) != 0:
                            oct2 = Q(ipv6__block2__iexact=blocks[1])
                        if len(blocks[2]) != 0:
                            oct3 = Q(ipv6__block3__iexact=blocks[2])
                        if len(blocks[3]) != 0:
                            oct4 = Q(ipv6__block4__iexact=blocks[3])
                        if len(blocks[4]) != 0:
                            oct5 = Q(ipv6__block5__iexact=blocks[4])
                        if len(blocks[5]) != 0:
                            oct6 = Q(ipv6__block6__iexact=blocks[5])
                        if len(blocks[6]) != 0:
                            oct7 = Q(ipv6__block7__iexact=blocks[6])
                        if len(blocks[7]) != 0:
                            oct8 = Q(ipv6__block8__iexact=blocks[7])

                        vip = vip.filter(oct1 & oct2 & oct3 & oct4 & oct5
                                         & oct6 & oct7 & oct8)

            vip = vip.distinct()

            vip = vip.order_by("-pk")

            # Datatable paginator
            vip, total = build_query_to_datatable(vip, asorting_cols,
                                                  custom_search,
                                                  searchable_columns,
                                                  start_record, end_record)

            itens = get_vips(vip)

            vip_map = dict()
            vip_map["vips"] = itens
            vip_map["total"] = total

            return self.response(dumps_networkapi(vip_map))
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to add block in vip rule.

        URLs: /vip/add_block/<id_vip>/<id_block>/<override>
        """

        self.log.info('Add block in rule vip')

        try:
            # Commons Validations

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

            # Business Validations
            id_vip = kwargs.get('id_vip')
            id_block = kwargs.get('id_block')
            override = kwargs.get('override')

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

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

            if not is_valid_boolean_param(override, False):
                self.log.error(u'Parameter override is invalid. Value: %s.',
                               override)
                raise InvalidValueError(None, 'override', override)
            else:
                override = convert_string_or_int_to_boolean(override)

            vip = RequisicaoVips.get_by_pk(id_vip)
            vip_map = vip.variables_to_map()
            host = vip_map['host']
            rule_applied = vip.rule_applied

            # Vip must be created
            if not vip.vip_criado:
                self.log.error(
                    u'Block can not added because VIP has not been created yet.'
                )
                raise RequestVipsNotBeenCreatedError(None)

            ###################################################
            #         Vip Request has a rule applied          #
            ###################################################
            if rule_applied:
                block_in_rules = self.insert_block_in_rule(
                    id_block, rule_applied)

                # create new rule
                # make a copy
                new_rule_content = copy.copy(rule_applied)

                # remove the rule if is a vip rule and this rule is not applied
                if vip.rule:
                    if rule_applied != vip.rule and vip.rule.vip:
                        vip.rule.delete()

                # duplicate rule with new block
                new_rule_content.id = None
                new_rule_content.vip = vip
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.save(user, force_insert=True)

            ###################################################
            #        Vip Request hasn't a rule applied        #
            ###################################################
            else:
                block_in_rules, environment = self.generate_rule_contents(
                    vip, id_block)

                # create new rule
                new_rule_content = Rule()
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.vip = vip
                new_rule_content.environment = environment
                new_rule_content.save()

            new_content = '\n'.join(d['content'] for d in block_in_rules)

            # save contents with new rule
            for i in range(len(block_in_rules)):
                rule_content = RuleContent()
                rule_content.content = block_in_rules[i]['content']
                rule_content.order = i
                rule_content.rule = new_rule_content
                rule_content.save()

            if override or not vip.l7_filter:
                # update filter and rule with new block
                vip.l7_filter = new_content
                vip.rule = new_rule_content
                vip.filter_valid = True
                vip.save()
            else:
                self.log.error(
                    u'Block can not be added because there is already a rule to apply, and the value of zero is overwritten.'
                )
                raise AddBlockOverrideNotDefined(None)

            success_map = dict()
            success_map['codigo'] = 0
            success_map['descricao'] = u'Bloco incluído com sucesso'

            return self.response(dumps_networkapi({'sucesso': success_map}))

        except VipRequestBlockAlreadyInRule, e:
            self.log.error(e.message)
            return self.response_error(361)
Exemple #15
0
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to authenticate to user.

        URL: authenticate/
        """

        try:

            self.log.info('Authenticate user')

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

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

            # Get XML data
            username = user_map.get('username')
            password = user_map.get('password')
            is_ldap_user = user_map.get('is_ldap_user')

            # Username can NOT be less 3 and greater than 45
            if not is_valid_string_minsize(username, 3) or not is_valid_string_maxsize(username, 45):
                self.log.error(
                    u'Parameter username is invalid. Value: %s.', username)
                raise InvalidValueError(None, 'username', username)

            if not is_valid_boolean_param(is_ldap_user):
                self.log.error(
                    u'Parameter is_ldap_user is invalid. Value: %s.', is_ldap_user)
                raise InvalidValueError(None, 'is_ldap_user', is_ldap_user)
            else:
                is_ldap_user = convert_string_or_int_to_boolean(is_ldap_user)

            if is_ldap_user:
                user = Usuario().get_by_ldap_user(username, True)
                password = user.pwd
            else:
                # Password can NOT be less 3 and greater than 45
                if not is_valid_string_minsize(password, 3) or not is_valid_string_maxsize(password, 45):
                    self.log.error(
                        u'Parameter password is invalid. Value: %s.', '****')
                    raise InvalidValueError(None, 'password', '****')

                # Find user by username, password to check if it exist
                user = Usuario().get_enabled_user(username.upper(), password)

            # Valid user
            if user is None:
                return self.response(dumps_networkapi({}))

            perms = {}
            for ugroup in user.grupos.all():

                for perm in ugroup.permissaoadministrativa_set.all():

                    function = perm.permission.function

                    if function in perms:

                        write = False
                        read = False

                        if perms.get(function).get('write') is True or perm.escrita is True:
                            write = True

                        if perms.get(function).get('read') is True or perm.leitura is True:
                            read = True

                        perms[function] = {'write': write, 'read': read}

                    else:
                        perms[function] = {
                            'write': perm.escrita, 'read': perm.leitura}

            user_map = {}
            user_dict = model_to_dict(
                user, fields=['id', 'user', 'nome', 'email', 'ativo', 'user_ldap'])
            user_dict['pwd'] = password
            user_dict['permission'] = perms
            user_map['user'] = user_dict

            return self.response(dumps_networkapi(user_map))

        except UsuarioNotFoundError:
            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 find all VLANs by search parameters.

        URLs: /vlan/find/
        """

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

        try:

            # Commons Validations

            # User permission
            if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.READ_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, ['searchable_columns', 'asorting_cols'])

            # 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
            start_record = vlan_map.get('start_record')
            end_record = vlan_map.get('end_record')
            asorting_cols = vlan_map.get('asorting_cols')
            searchable_columns = vlan_map.get('searchable_columns')
            custom_search = vlan_map.get('custom_search')

            number = vlan_map.get('numero')
            name = vlan_map.get('nome')
            iexact = vlan_map.get('exato')
            environment = vlan_map.get('ambiente')
            net_type = vlan_map.get('tipo_rede')
            network = vlan_map.get('rede')
            ip_version = vlan_map.get('versao')
            subnet = vlan_map.get('subrede')
            acl = vlan_map.get('acl')

            # Business Rules

            # Start with alls
            vlans = Vlan.objects.all().prefetch_related(
                'networkipv4_set', 'networkipv6_set')

            if number is not None:
                # If number is valid, add to filter
                if not is_valid_int_greater_zero_param(number, False):
                    raise InvalidValueError(None, 'numero', number)
                else:
                    vlans = vlans.filter(num_vlan=number)

            if name is not None:
                # If name is valid, add to filter
                if not is_valid_string_minsize(name, 3, False):
                    raise InvalidValueError(None, 'nome', name)
                else:
                    # Iexact must be valid to add name to filter
                    if not is_valid_boolean_param(iexact, False):
                        raise InvalidValueError(None, 'exato', iexact)
                    else:
                        if (iexact is None) or (iexact == 'False') or (iexact == '0'):
                            iexact = False

                        if iexact:
                            vlans = vlans.filter(nome=name)
                        else:
                            vlans = vlans.filter(nome__icontains=name)

            # If environment is valid, add to filter
            if environment is not None:
                if not is_valid_int_greater_zero_param(environment, False):
                    raise InvalidValueError(None, 'ambiente', environment)
                else:
                    vlans = vlans.filter(ambiente__pk=environment)

            if net_type is not None:
                # If net_type is valid, add to filter
                if not is_valid_int_greater_zero_param(net_type, False):
                    raise InvalidValueError(None, 'tipo_rede', net_type)
                else:
                    q1 = Q(networkipv4__network_type__id=net_type)
                    q2 = Q(networkipv6__network_type__id=net_type)
                    vlans = vlans.filter(q1 | q2)

            if acl is not None:
                # If acl is valid, add to filter
                if not is_valid_boolean_param(acl, False):
                    raise InvalidValueError(None, 'acl', acl)
                else:
                    if (acl is None) or (acl == 'False') or (acl == '0'):
                        acl = False
                    # If acl is true, only show vlans with false acl_valida
                    if acl:
                        vlans = vlans.filter(acl_valida=False)

            # If ip_version is valid
            if not is_valid_int_greater_equal_zero_param(ip_version):
                raise InvalidValueError(None, 'versao', ip_version)
            else:
                if ip_version == '0':
                    vlans = vlans.filter(
                        Q(networkipv6__isnull=True) | Q(networkipv4__isnull=False))
                elif ip_version == '1':
                    vlans = vlans.filter(
                        Q(networkipv4__isnull=True) | Q(networkipv6__isnull=False))

            if network is not None:
                # If network is valid
                if not is_valid_string_minsize(network, 1, False):
                    raise InvalidValueError(None, 'rede', network)
                else:
                    blocks, network, version = break_network(network)
                    try:
                        network_ip = IPNetwork(network)
                    except ValueError, e:
                        raise InvalidValueError(None, 'rede', network)

                # If subnet is valid, add to filter
                if not (subnet == '0' or subnet == '1'):
                    raise InvalidValueError(None, 'subrede', subnet)
                else:
                    # If subnet is 0, only filter network octs
                    if subnet == '0':

                        # Filter octs
                        if version == IP_VERSION.IPv4[0]:
                            # Network IP v4
                            oct1 = Q()
                            oct2 = Q()
                            oct3 = Q()
                            oct4 = Q()
                            blk = Q()

                            if len(blocks[0]) != 0:
                                oct1 = Q(networkipv4__oct1=blocks[0])
                            if len(blocks[1]) != 0:
                                oct2 = Q(networkipv4__oct2=blocks[1])
                            if len(blocks[2]) != 0:
                                oct3 = Q(networkipv4__oct3=blocks[2])
                            if len(blocks[3]) != 0:
                                oct4 = Q(networkipv4__oct4=blocks[3])
                            if len(blocks[4]) != 0:
                                blk = Q(networkipv4__block=blocks[4])

                            vlans = vlans.filter(
                                oct1 & oct2 & oct3 & oct4 & blk)
                        else:
                            # Network IP v6
                            oct1 = Q()
                            oct2 = Q()
                            oct3 = Q()
                            oct4 = Q()
                            oct5 = Q()
                            oct6 = Q()
                            oct7 = Q()
                            oct8 = Q()
                            blk = Q()

                            if len(blocks[0]) != 0:
                                oct1 = Q(networkipv6__block1__iexact=blocks[0])
                            if len(blocks[1]) != 0:
                                oct2 = Q(networkipv6__block2__iexact=blocks[1])
                            if len(blocks[2]) != 0:
                                oct3 = Q(networkipv6__block3__iexact=blocks[2])
                            if len(blocks[3]) != 0:
                                oct4 = Q(networkipv6__block4__iexact=blocks[3])
                            if len(blocks[4]) != 0:
                                oct5 = Q(networkipv6__block5__iexact=blocks[4])
                            if len(blocks[5]) != 0:
                                oct6 = Q(networkipv6__block6__iexact=blocks[5])
                            if len(blocks[6]) != 0:
                                oct7 = Q(networkipv6__block7__iexact=blocks[6])
                            if len(blocks[7]) != 0:
                                oct8 = Q(networkipv6__block8__iexact=blocks[7])
                            if len(blocks[8]) != 0:
                                blk = Q(networkipv6__block=blocks[8])

                            vlans = vlans.filter(
                                oct1 & oct2 & oct3 & oct4 & oct5 & oct6 & oct7 & oct8 & blk)
                    # If subnet is 1
                    else:

                        if version == IP_VERSION.IPv4[0]:
                            expl = split(network_ip.network.exploded, '.')
                        else:
                            expl = split(network_ip.network.exploded, ':')

                        expl.append(str(network_ip.prefixlen))

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

                        # First, get all vlans filtered until now
                        itens = get_networks_simple(vlans)

                        ids_exclude = []
                        # Then iterate over it to verify each vlan
                        for vlan in itens:

                            is_subnet = verify_subnet(
                                vlan, network_ip, version)
                            if not is_subnet:
                                ids_exclude.append(vlan['id'])

                        vlans = vlans.exclude(id__in=ids_exclude)

            # Custom order
            if asorting_cols:
                if 'ambiente' in asorting_cols:
                    vlans = vlans.order_by(
                        'ambiente__divisao_dc__nome', 'ambiente__ambiente_logico__nome', 'ambiente__grupo_l3__nome')
                    asorting_cols.remove('ambiente')
                if '-ambiente' in asorting_cols:
                    vlans = vlans.order_by(
                        '-ambiente__divisao_dc__nome', '-ambiente__ambiente_logico__nome', '-ambiente__grupo_l3__nome')
                    asorting_cols.remove('-ambiente')
                if 'tipo_rede' in asorting_cols:
                    vlans = vlans.order_by(
                        'networkipv4__network_type__tipo_rede', 'networkipv6__network_type__tipo_rede')
                    asorting_cols.remove('tipo_rede')
                if '-tipo_rede' in asorting_cols:
                    vlans = vlans.order_by(
                        '-networkipv4__network_type__tipo_rede', '-networkipv6__network_type__tipo_rede')
                    asorting_cols.remove('-tipo_rede')
                if 'network' in asorting_cols:
                    vlans = vlans.order_by('networkipv4__oct1', 'networkipv4__oct2', 'networkipv4__oct3', 'networkipv4__oct4', 'networkipv4__block', 'networkipv6__block1', 'networkipv6__block2',
                                           'networkipv6__block3', 'networkipv6__block4', 'networkipv6__block5', 'networkipv6__block6', 'networkipv6__block7', 'networkipv6__block8', 'networkipv6__block')
                    asorting_cols.remove('network')
                if '-network' in asorting_cols:
                    vlans = vlans.order_by('-networkipv4__oct1', '-networkipv4__oct2', '-networkipv4__oct3', '-networkipv4__oct4', '-networkipv4__block', '-networkipv6__block1', '-networkipv6__block2',
                                           '-networkipv6__block3', '-networkipv6__block4', '-networkipv6__block5', '-networkipv6__block6', '-networkipv6__block7', '-networkipv6__block8', '-networkipv6__block')
                    asorting_cols.remove('-network')

            vlans = vlans.distinct()

            # Datatable paginator
            vlans, total = build_query_to_datatable(
                vlans, asorting_cols, custom_search, searchable_columns, start_record, end_record)
            vlans = vlans.prefetch_related('ambiente',
                                           'networkipv4_set__network_type',
                                           'networkipv4_set__ip_set__ipequipamento_set__equipamento__equipamentoambiente_set__ambiente',
                                           'networkipv6_set__network_type',
                                           'networkipv6_set__ipv6_set__ipv6equipament_set__equipamento__equipamentoambiente_set__ambiente')

            itens = get_networks(vlans, False)

            vlan_map = dict()
            vlan_map['vlan'] = itens
            vlan_map['total'] = total

            return self.response(dumps_networkapi(vlan_map))
    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to add block in vip rule.

        URLs: /vip/add_block/<id_vip>/<id_block>/<override>
        """

        self.log.info('Add block in rule vip')

        try:
            # Commons Validations

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

            # Business Validations
            id_vip = kwargs.get('id_vip')
            id_block = kwargs.get('id_block')
            override = kwargs.get('override')

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

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

            if not is_valid_boolean_param(override, False):
                self.log.error(
                    u'Parameter override is invalid. Value: %s.', override)
                raise InvalidValueError(None, 'override', override)
            else:
                override = convert_string_or_int_to_boolean(override)

            vip = RequisicaoVips.get_by_pk(id_vip)
            vip_map = vip.variables_to_map()
            host = vip_map['host']
            rule_applied = vip.rule_applied

            # Vip must be created
            if not vip.vip_criado:
                self.log.error(
                    u'Block can not added because VIP has not been created yet.')
                raise RequestVipsNotBeenCreatedError(None)

            ###################################################
            #         Vip Request has a rule applied          #
            ###################################################
            if rule_applied:
                block_in_rules = self.insert_block_in_rule(
                    id_block, rule_applied)

                # create new rule
                # make a copy
                new_rule_content = copy.copy(rule_applied)

                # remove the rule if is a vip rule and this rule is not applied
                if vip.rule:
                    if rule_applied != vip.rule and vip.rule.vip:
                        vip.rule.delete()

                # duplicate rule with new block
                new_rule_content.id = None
                new_rule_content.vip = vip
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.save(user, force_insert=True)

            ###################################################
            #        Vip Request hasn't a rule applied        #
            ###################################################
            else:
                block_in_rules, environment = self.generate_rule_contents(
                    vip, id_block)

                # create new rule
                new_rule_content = Rule()
                count_rule_vip = Rule.objects.filter(vip=vip).count()
                diff_name = '(' + str(count_rule_vip) + \
                    ')' if count_rule_vip else ''
                new_rule_content.name = 'regra_' + host + diff_name
                new_rule_content.vip = vip
                new_rule_content.environment = environment
                new_rule_content.save()

            new_content = '\n'.join(d['content'] for d in block_in_rules)

            # save contents with new rule
            for i in range(len(block_in_rules)):
                rule_content = RuleContent()
                rule_content.content = block_in_rules[i]['content']
                rule_content.order = i
                rule_content.rule = new_rule_content
                rule_content.save()

            if override or not vip.l7_filter:
                # update filter and rule with new block
                vip.l7_filter = new_content
                vip.rule = new_rule_content
                vip.filter_valid = True
                vip.save()
            else:
                self.log.error(
                    u'Block can not be added because there is already a rule to apply, and the value of zero is overwritten.')
                raise AddBlockOverrideNotDefined(None)

            success_map = dict()
            success_map['codigo'] = 0
            success_map['descricao'] = u'Bloco incluído com sucesso'

            return self.response(dumps_networkapi({'sucesso': success_map}))

        except VipRequestBlockAlreadyInRule, e:
            self.log.error(e.message)
            return self.response_error(361)
    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to authenticate to user.

        URL: authenticate/
        """

        try:

            self.log.info("Authenticate user")

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

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

            # Get XML data
            username = user_map.get('username')
            password = user_map.get('password')
            is_ldap_user = user_map.get('is_ldap_user')

            # Username can NOT be less 3 and greater than 45
            if not is_valid_string_minsize(username, 3) or not is_valid_string_maxsize(username, 45):
                self.log.error(
                    u'Parameter username is invalid. Value: %s.', username)
                raise InvalidValueError(None, 'username', username)

            if not is_valid_boolean_param(is_ldap_user):
                self.log.error(
                    u'Parameter is_ldap_user is invalid. Value: %s.', is_ldap_user)
                raise InvalidValueError(None, 'is_ldap_user', is_ldap_user)
            else:
                is_ldap_user = convert_string_or_int_to_boolean(is_ldap_user)

            if is_ldap_user:
                user = Usuario().get_by_ldap_user(username, True)
                password = user.pwd
            else:
                # Password can NOT be less 3 and greater than 45
                if not is_valid_string_minsize(password, 3) or not is_valid_string_maxsize(password, 45):
                    self.log.error(
                        u'Parameter password is invalid. Value: %s.', '****')
                    raise InvalidValueError(None, 'password', '****')

                # Find user by username, password to check if it exist
                user = Usuario().get_enabled_user(username.upper(), password)

            # Valid user
            if user is None:
                return self.response(dumps_networkapi({}))

            perms = {}
            for ugroup in user.grupos.all():

                for perm in ugroup.permissaoadministrativa_set.all():

                    function = perm.permission.function

                    if perms.has_key(function):

                        write = False
                        read = False

                        if perms.get(function).get('write') == True or perm.escrita == True:
                            write = True

                        if perms.get(function).get('read') == True or perm.leitura == True:
                            read = True

                        perms[function] = {'write': write, 'read': read}

                    else:
                        perms[function] = {
                            'write': perm.escrita, 'read': perm.leitura}

            user_map = {}
            user_dict = model_to_dict(
                user, fields=['id', 'user', 'nome', 'email', 'ativo', 'user_ldap'])
            user_dict['pwd'] = password
            user_dict['permission'] = perms
            user_map['user'] = user_dict

            return self.response(dumps_networkapi(user_map))

        except UsuarioNotFoundError:
            return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit User.

        URL: user/<id_user>/
        """
        try:

            self.log.info('Edit User')

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

            id_user = kwargs.get('id_user')

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

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

            # Get XML data
            username = user_map.get('user')
            password = user_map.get('password')
            name = user_map.get('name')
            email = user_map.get('email')
            active = user_map.get('active')
            user_ldap = user_map.get('user_ldap')

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

            # Valid username
            if not is_valid_string_minsize(username, 3) or not is_valid_string_maxsize(username, 45):
                self.log.error(
                    u'Parameter user is invalid. Value: %s', username)
                raise InvalidValueError(None, 'user', username)

            # Valid pwd
            if not is_valid_string_minsize(password, 3) or not is_valid_string_maxsize(password, 45):
                self.log.error(u'Parameter password is invalid. Value: ****')
                raise InvalidValueError(None, 'password', '****')

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

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

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

            # Valid LDAP username
            if not is_valid_string_minsize(user_ldap, 3, False) or not is_valid_string_maxsize(user_ldap, 45, False):
                self.log.error(
                    u'Parameter user_ldap is invalid. Value: %s', user_ldap)
                raise InvalidValueError(None, 'user_ldap', user_ldap)

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            with distributedlock(LOCK_USER % id_user):

                try:
                    if usr.user.lower() != username.lower():
                        Usuario.get_by_user(username)
                        raise UsuarioNameDuplicatedError(
                            None, u'Já existe um usuário com o valor user %s.' % username)
                except UsuarioNotFoundError:
                    pass

                # set variables
                usr.user = username
                usr.pwd = password
                usr.nome = name
                usr.email = email
                usr.ativo = convert_string_or_int_to_boolean(active)
                usr.user_ldap = user_ldap

                try:
                    # update User
                    usr.save()
                except Exception, e:
                    self.log.error(u'Failed to update the user.')
                    raise UsuarioError(e, u'Failed to update the user.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
    def handle_put(self, request, user, *args, **kwargs):
        """Trata uma requisição PUT para alterar informações de uma interface.

        URL: /interface/<id_interface>/
        """

        # Get request data and check permission
        try:
            # Valid Interface ID
            id_interface = kwargs.get('id_interface')
            if not is_valid_int_greater_zero_param(id_interface):
                self.log.error(
                    u'The id_interface parameter is not a valid value: %s.', id_interface)
                raise InvalidValueError(None, 'id_interface', id_interface)

            # Get interface and equipment to check permission
            interface = Interface.get_by_pk(id_interface)
            id_equipamento = interface.equipamento_id

            # Check permission
            if not has_perm(user,
                            AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            # Get XML data
            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 XML request.')

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

            # Valid name value
            nome = interface_map.get('nome')
            if not is_valid_string_minsize(nome, 1) or not is_valid_string_maxsize(nome, 20):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)

            # Valid protegida value
            protegida = interface_map.get('protegida')
            if not is_valid_boolean_param(protegida):
                self.log.error(
                    u'Parameter protegida is invalid. Value: %s', protegida)
                raise InvalidValueError(None, 'protegida', protegida)
            else:
                protegida = convert_string_or_int_to_boolean(protegida)

            # Valid descricao value
            descricao = interface_map.get('descricao')
            if descricao is not None:
                if not is_valid_string_minsize(descricao, 3) or not is_valid_string_maxsize(descricao, 200):
                    self.log.error(
                        u'Parameter descricao is invalid. Value: %s', descricao)
                    raise InvalidValueError(None, 'descricao', descricao)

            # Valid "id_ligacao_front" value
            id_ligacao_front = interface_map.get('id_ligacao_front')
            if id_ligacao_front is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_front):
                    self.log.error(
                        u'The id_ligacao_front parameter is not a valid value: %s.', id_ligacao_front)
                    raise InvalidValueError(
                        None, 'id_ligacao_front', id_ligacao_front)
                else:
                    id_ligacao_front = int(id_ligacao_front)

            # Valid "id_ligacao_back" value
            id_ligacao_back = interface_map.get('id_ligacao_back')
            if id_ligacao_back is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_back):
                    self.log.error(
                        u'The id_ligacao_back parameter is not a valid value: %s.', id_ligacao_back)
                    raise InvalidValueError(
                        None, 'id_ligacao_back', id_ligacao_back)
                else:
                    id_ligacao_back = int(id_ligacao_back)

            tipo = interface_map.get('tipo')
            tipo = TipoInterface.get_by_name(tipo)

            vlan = interface_map.get('vlan')

            with distributedlock(LOCK_INTERFACE % id_interface):

                # Update interface
                Interface.update(user,
                                 id_interface,
                                 interface=nome,
                                 protegida=protegida,
                                 descricao=descricao,
                                 ligacao_front_id=id_ligacao_front,
                                 ligacao_back_id=id_ligacao_back,
                                 tipo=tipo,
                                 vlan_nativa=vlan)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Exemple #21
0
    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para criar uma nova interface para o equipamento

        URL: /interface/

        """
        # Obtém dados do request e verifica acesso
        try:

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

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

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

            # Valid id_equipamento value
            id_equipamento = interface_map.get('id_equipamento')
            if not is_valid_int_greater_zero_param(id_equipamento):
                self.log.error(
                    u'Parameter id_equipamento is invalid. Value: %s',
                    id_equipamento)
                raise InvalidValueError(None, 'id_equipamento', id_equipamento)
            else:
                id_equipamento = int(id_equipamento)

            # Check existence
            Equipamento.get_by_pk(id_equipamento)

            # Verify permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION, None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            # Valid name value
            nome = interface_map.get('nome')
            if not is_valid_string_minsize(
                    nome, 1) or not is_valid_string_maxsize(nome, 20):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)

            # Valid protegida value
            protegida = interface_map.get('protegida')
            if not is_valid_boolean_param(protegida):
                self.log.error(u'Parameter protegida is invalid. Value: %s',
                               protegida)
                raise InvalidValueError(None, 'protegida', protegida)
            else:
                protegida = convert_string_or_int_to_boolean(protegida)

            # Valid descricao value
            descricao = interface_map.get('descricao')
            if descricao is not None:
                if not is_valid_string_minsize(
                        descricao, 3) or not is_valid_string_maxsize(
                            descricao, 200):
                    self.log.error(
                        u'Parameter descricao is invalid. Value: %s',
                        descricao)
                    raise InvalidValueError(None, 'descricao', descricao)

            # Valid "id_ligacao_front" value
            id_ligacao_front = interface_map.get('id_ligacao_front')
            if id_ligacao_front is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_front):
                    self.log.error(
                        u'The id_ligacao_front parameter is not a valid value: %s.',
                        id_ligacao_front)
                    raise InvalidValueError(None, 'id_ligacao_front',
                                            id_ligacao_front)
                else:
                    id_ligacao_front = int(id_ligacao_front)
                    ligacao_front = Interface(id=id_ligacao_front)
            else:
                ligacao_front = None

            # Valid "id_ligacao_back" value
            id_ligacao_back = interface_map.get('id_ligacao_back')
            if id_ligacao_back is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_back):
                    self.log.error(
                        u'The id_ligacao_back parameter is not a valid value: %s.',
                        id_ligacao_back)
                    raise InvalidValueError(None, 'id_ligacao_back',
                                            id_ligacao_back)
                else:
                    id_ligacao_back = int(id_ligacao_back)
                    ligacao_back = Interface(id=id_ligacao_back)
            else:
                ligacao_back = None

            tipo_interface = interface_map.get('tipo')
            if tipo_interface is None:
                tipo_interface = 'Access'
            tipo_interface = TipoInterface.get_by_name(tipo_interface)

            vlan = interface_map.get('vlan')

            # Cria a interface conforme dados recebidos no XML
            interface = Interface(interface=nome,
                                  protegida=protegida,
                                  descricao=descricao,
                                  ligacao_front=ligacao_front,
                                  ligacao_back=ligacao_back,
                                  equipamento=Equipamento(id=id_equipamento),
                                  tipo=tipo_interface,
                                  vlan_nativa=vlan)

            interface.create(user)

            networkapi_map = dict()
            interface_map = dict()

            interface_map['id'] = interface.id
            networkapi_map['interface'] = interface_map

            return self.response(dumps_networkapi(networkapi_map))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Exemple #22
0
    def handle_put(self, request, user, *args, **kwargs):
        """Treat requests PUT to edit Administrative Permission.

        URL: perms/<id_perm>/
        """
        try:

            self.log.info("Edit Administrative Permission")

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

            id_perm = kwargs.get('id_perm')

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

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

            # Get XML data
            id_permission = perm_map.get('id_permission')
            id_group = perm_map.get('id_group')
            read = perm_map.get('read')
            write = perm_map.get('write')

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

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

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

            # Valid Read
            if not is_valid_boolean_param(read):
                self.log.error(u'The read parameter is not a valid value: %s.',
                               read)
                raise InvalidValueError(None, 'read', read)

            # Valid Read
            if not is_valid_boolean_param(write):
                self.log.error(
                    u'The write parameter is not a valid value: %s.', write)
                raise InvalidValueError(None, 'write', write)

            # Find Permission by ID to check if it exist
            adm_perm = PermissaoAdministrativa.get_by_pk(id_perm)

            with distributedlock(LOCK_PERM % id_perm):

                # Find Permission by ID to check if it exist
                permission = Permission.get_by_pk(id_permission)

                # Find UGroup by ID to check if it exist
                ugroup = UGrupo.get_by_pk(id_group)

                try:
                    perm = PermissaoAdministrativa.get_permission_by_permission_ugroup(
                        id_permission, id_group)
                    if perm.id != int(id_perm):
                        raise PermissaoAdministrativaDuplicatedError(
                            None, permission.function)
                except PermissaoAdministrativaNotFoundError:
                    pass

                # set variables
                adm_perm.permission = permission
                adm_perm.ugrupo = ugroup
                adm_perm.leitura = convert_string_or_int_to_boolean(read)
                adm_perm.escrita = convert_string_or_int_to_boolean(write)

                try:
                    # update Administrative Permission
                    adm_perm.save()
                except Exception, e:
                    self.log.error(
                        u'Failed to update the administrative permission.')
                    raise PermissionError(
                        e, u'Failed to update the administrative permission.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
Exemple #23
0
    def handle_put(self, request, user, *args, **kwargs):
        """Trata uma requisição PUT para alterar informações de uma interface.

        URL: /interface/<id_interface>/
        """

        # Get request data and check permission
        try:
            # Valid Interface ID
            id_interface = kwargs.get('id_interface')
            if not is_valid_int_greater_zero_param(id_interface):
                self.log.error(
                    u'The id_interface parameter is not a valid value: %s.',
                    id_interface)
                raise InvalidValueError(None, 'id_interface', id_interface)

            # Get interface and equipment to check permission
            interface = Interface.get_by_pk(id_interface)
            id_equipamento = interface.equipamento_id

            # Check permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION, None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            # Get XML data
            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 XML request.')

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

            # Valid name value
            nome = interface_map.get('nome')
            if not is_valid_string_minsize(
                    nome, 1) or not is_valid_string_maxsize(nome, 20):
                self.log.error(u'Parameter nome is invalid. Value: %s', nome)
                raise InvalidValueError(None, 'nome', nome)

            # Valid protegida value
            protegida = interface_map.get('protegida')
            if not is_valid_boolean_param(protegida):
                self.log.error(u'Parameter protegida is invalid. Value: %s',
                               protegida)
                raise InvalidValueError(None, 'protegida', protegida)
            else:
                protegida = convert_string_or_int_to_boolean(protegida)

            # Valid descricao value
            descricao = interface_map.get('descricao')
            if descricao is not None:
                if not is_valid_string_minsize(
                        descricao, 3) or not is_valid_string_maxsize(
                            descricao, 200):
                    self.log.error(
                        u'Parameter descricao is invalid. Value: %s',
                        descricao)
                    raise InvalidValueError(None, 'descricao', descricao)

            # Valid "id_ligacao_front" value
            id_ligacao_front = interface_map.get('id_ligacao_front')
            if id_ligacao_front is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_front):
                    self.log.error(
                        u'The id_ligacao_front parameter is not a valid value: %s.',
                        id_ligacao_front)
                    raise InvalidValueError(None, 'id_ligacao_front',
                                            id_ligacao_front)
                else:
                    id_ligacao_front = int(id_ligacao_front)

            # Valid "id_ligacao_back" value
            id_ligacao_back = interface_map.get('id_ligacao_back')
            if id_ligacao_back is not None:
                if not is_valid_int_greater_zero_param(id_ligacao_back):
                    self.log.error(
                        u'The id_ligacao_back parameter is not a valid value: %s.',
                        id_ligacao_back)
                    raise InvalidValueError(None, 'id_ligacao_back',
                                            id_ligacao_back)
                else:
                    id_ligacao_back = int(id_ligacao_back)

            tipo = interface_map.get('tipo')
            if tipo is not None:
                tipo = TipoInterface.get_by_name(tipo)

            vlan = interface_map.get('vlan')
            with distributedlock(LOCK_INTERFACE % id_interface):

                # Update interface
                Interface.update(user,
                                 id_interface,
                                 interface=nome,
                                 protegida=protegida,
                                 descricao=descricao,
                                 ligacao_front_id=id_ligacao_front,
                                 ligacao_back_id=id_ligacao_back,
                                 tipo=tipo,
                                 vlan_nativa=vlan)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
def insert_equipment(equipment_map, user):
    '''
    Insere um equipamento e o relacionamento entre equipamento e o grupo.

    @param equipment_map: Map com as chaves: id_grupo, id_tipo_equipamento, id_modelo e nome
    @param user: Usuário autenticado na API.

    @return Em caso de erro retorna a tupla: (código da mensagem de erro, argumento01, argumento02, ...)
            Em caso de sucesso retorna a tupla: (0, <identificador do equipamento_grupo>, <equipamento>)

    @raise InvalidGroupToEquipmentTypeError: Equipamento do grupo “Equipamentos Orquestração” somente poderá ser criado com tipo igual a “Servidor Virtual”.

    @raise EGrupoNotFoundError: Grupo não cadastrado. 

    @raise GrupoError: Falha ao pesquisar o Grupo. 

    @raise TipoEquipamentoNotFoundError: Tipo de equipamento nao cadastrado.

    @raise ModeloNotFoundError: Modelo nao cadastrado.

    @raise EquipamentoNameDuplicatedError: Nome do equipamento duplicado.

    @raise EquipamentoError: Falha ou inserir o equipamento.

    @raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.  

    '''
    log = Log('insert_equipment')

    log.debug('EQUIPAMENTO_MAP: %s', equipment_map)

    equipment = Equipamento()
    equipment.tipo_equipamento = TipoEquipamento()
    equipment.modelo = Modelo()

    group_id = equipment_map.get('id_grupo')
    if not is_valid_int_greater_zero_param(group_id):
        log.error(
            u'The group_id parameter is not a valid value: %s.', group_id)
        raise InvalidValueError(None, 'group_id', group_id)
    else:
        group_id = int(group_id)

    if not has_perm(user,
                    AdminPermission.EQUIPMENT_MANAGEMENT,
                    AdminPermission.WRITE_OPERATION,
                    group_id,
                    None,
                    AdminPermission.EQUIP_WRITE_OPERATION):
        raise UserNotAuthorizedError(
            None, u'Usuário não tem permissão para executar a operação.')

    equipment_type_id = equipment_map.get('id_tipo_equipamento')
    if not is_valid_int_greater_zero_param(equipment_type_id):
        log.error(
            u'The equipment_type_id parameter is not a valid value: %s.', equipment_type_id)
        raise InvalidValueError(None, 'equipment_type_id', equipment_type_id)
    else:
        equipment.tipo_equipamento.id = int(equipment_type_id)

    model_id = equipment_map.get('id_modelo')
    if not is_valid_int_greater_zero_param(model_id):
        log.error(
            u'The model_id parameter is not a valid value: %s.', model_id)
        raise InvalidValueError(None, 'model_id', model_id)
    else:
        equipment.modelo.id = int(model_id)

    name = equipment_map.get('nome')
    if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 50):
        log.error(u'The name parameter is not a valid value: %s.', name)
        raise InvalidValueError(None, 'name', name)
    else:
        equipment.nome = name

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

    equipment_group_id = equipment.create(user, group_id)

    return 0, equipment_group_id, equipment
    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)