• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python distributedlock.distributedlock函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中networkapi.distributedlock.distributedlock函数的典型用法代码示例。如果您正苦于以下问题:Python distributedlock函数的具体用法?Python distributedlock怎么用?Python distributedlock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了distributedlock函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: deploy_networkIPv6_configuration

def deploy_networkIPv6_configuration(user, networkipv6, equipment_list):
	'''Loads template for creating Network IPv6 equipment configuration, creates file and
	apply config.

	Args: NetworkIPv6 object
	Equipamento objects list

	Returns: List with status of equipments output
	'''

	data = dict()
	#lock network id to prevent multiple requests to same id
	with distributedlock(LOCK_NETWORK_IPV6 % networkipv6.id):
		with distributedlock(LOCK_VLAN % networkipv6.vlan.id):
			if networkipv6.active == 1:
				data["output"] = "Network already active. Nothing to do."
				return data

			#load dict with all equipment attributes
			dict_ips = get_dict_v6_to_use_in_configuration_deploy(user, networkipv6, equipment_list)
			status_deploy = dict()
			#TODO implement threads
			for equipment in equipment_list:
				#generate config file
				file_to_deploy = _generate_config_file(dict_ips, equipment, TEMPLATE_NETWORKv6_ACTIVATE)
				#deploy config file in equipments
				lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_NETWORK_SCRIPT % (equipment.id)
				status_deploy[equipment.id] = deploy_config_in_equipment_synchronous(file_to_deploy, equipment, lockvar)
			
			networkipv6.activate(user)
			transaction.commit()
			if networkipv6.vlan.ativada == 0:
				networkipv6.vlan.activate(user)

			return status_deploy
开发者ID:williamvedroni-s2it,项目名称:GloboNetworkAPI,代码行数:35,代码来源:facade.py


示例2: remove_deploy_networkIPv6_configuration

def remove_deploy_networkIPv6_configuration(user, networkipv6, equipment_list):
    """Loads template for removing Network IPv6 equipment configuration, creates file and
    apply config.

    Args: NetworkIPv6 object
    Equipamento objects list

    Returns: List with status of equipments output
    """

    data = dict()

    # lock network id to prevent multiple requests to same id
    with distributedlock(LOCK_NETWORK_IPV6 % networkipv6.id):
        with distributedlock(LOCK_VLAN % networkipv6.vlan.id):
            if networkipv6.active == 0:
                data['output'] = 'Network already not active. Nothing to do.'
                return data

            # load dict with all equipment attributes
            dict_ips = get_dict_v6_to_use_in_configuration_deploy(
                user, networkipv6, equipment_list)
            status_deploy = dict()
            # TODO implement threads
            for equipment in equipment_list:
                # generate config file
                file_to_deploy = _generate_config_file(
                    dict_ips, equipment, TEMPLATE_NETWORKv6_DEACTIVATE)
                # deploy config file in equipments
                lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_NETWORK_SCRIPT % (
                    equipment.id)
                status_deploy[equipment.id] = deploy_config_in_equipment_synchronous(
                    file_to_deploy, equipment, lockvar)

            networkipv6.deactivate(user)
            transaction.commit()
            if networkipv6.vlan.ativada == 1:
                # if there are no other networks active in vlan, remove int
                # vlan
                if not _has_active_network_in_vlan(networkipv6.vlan):
                    # remove int vlan
                    for equipment in equipment_list:
                        if equipment.maintenance is not True:
                            status_deploy[
                                equipment.id] += _remove_svi(equipment, networkipv6.vlan.num_vlan)
                    networkipv6.vlan.remove(user)

            return status_deploy
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:48,代码来源:v1.py


示例3: handle_put

    def handle_put(self, request, user, *args, **kwargs):
        '''Trata as requisições de PUT para inserir o relacionamento entre IP e Equipamento.

        URL: ip/<id_ip>/equipamento/<id_equipamento>/$
        '''
        try:

            ip_id = kwargs.get('id_ip')
            equip_id = kwargs.get('id_equipamento')

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

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

            Ip.get_by_pk(ip_id)

            with distributedlock(LOCK_IP_EQUIPMENT % (ip_id, equip_id)):

                ip_equipment = insert_ip_equipment(ip_id, equip_id, user)

                ipequipamento_map = dict()
                ipequipamento_map['id'] = ip_equipment.id
                map = dict()
                map['ip_equipamento'] = ipequipamento_map

                return self.response(dumps_networkapi(map))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:34,代码来源:IpResource.py


示例4: create_dhcprelayIPv6_object

def create_dhcprelayIPv6_object(user, ipv6_id, networkipv6_id):

    with distributedlock(LOCK_DCHCPv6_NET % networkipv6_id):
        dhcprelay_obj = DHCPRelayIPv6()
        dhcprelay_obj.create(ipv6_id, networkipv6_id)
        dhcprelay_obj.save()
        return dhcprelay_obj
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:7,代码来源:v1.py


示例5: handle_delete

    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to remove Group User.

        URL: ugroup/<id_ugroup>/
        """
        try:

            self.log.info('Remove Group 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_ugroup = kwargs.get('id_ugroup')

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

            # Find Group User by ID to check if it exist
            ugroup = UGrupo.get_by_pk(id_ugroup)

            with distributedlock(LOCK_GROUP_USER % id_ugroup):

                ugroup.delete()
                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:33,代码来源:GroupUserAlterRemoveResource.py


示例6: deploy_config_in_equipment_synchronous

def deploy_config_in_equipment_synchronous(rel_filename, equipment, lockvar, tftpserver=None, equipment_access=None):
	'''Apply configuration file on equipment

	Args:
		rel_filename: relative file path from TFTPBOOT_FILES_PATH to apply in equipment
		equipment: networkapi.equipamento.Equipamento() or Equipamento().id
		lockvar: distributed lock variable to use when applying config to equipment
		equipment_access: networkapi.equipamento.EquipamentoAcesso() to use
		tftpserver: source TFTP server address

	Returns:
		equipment output

	Raises:
	'''

	#validate filename
	path = os.path.abspath(TFTPBOOT_FILES_PATH+rel_filename)
	if not path.startswith(TFTPBOOT_FILES_PATH):
		raise exceptions.InvalidFilenameException(rel_filename)

	if type(equipment) is int:
		equipment = Equipamento.get_by_pk(equipment)
	elif type(equipment) is Equipamento:
		pass
	else:
		log.error("Invalid data for equipment")
		raise api_exceptions.NetworkAPIException()

	with distributedlock(lockvar):
		return __applyConfig(equipment, rel_filename, equipment_access, tftpserver)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:31,代码来源:facade.py


示例7: handle_delete

    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to remove IP and Equipment relationship.

        URL: ip/<id_ip>/equipamento/<id_equipamento>/$
        """
        try:

            ip_id = kwargs.get('id_ip')
            equip_id = kwargs.get('id_equipamento')

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

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

            Ip.get_by_pk(ip_id)
            Equipamento.get_by_pk(equip_id)

            with distributedlock(LOCK_IP_EQUIPMENT % (ip_id, equip_id)):

                ipv4 = Ip.get_by_pk(ip_id)
                equipament = Equipamento.get_by_pk(equip_id)

                # Delete vlan's cache
                destroy_cache_function([ipv4])

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

                server_pool_member_list = ServerPoolMember.objects.filter(
                    ip=ipv4)

                if server_pool_member_list.count() != 0:
                    # IP associated with Server Pool

                    server_pool_name_list = set()

                    for member in server_pool_member_list:
                        item = '{}: {}'.format(
                            member.server_pool.id, member.server_pool.identifier)
                        server_pool_name_list.add(item)

                    server_pool_name_list = list(server_pool_name_list)
                    server_pool_identifiers = ', '.join(server_pool_name_list)

                    raise IpCantRemoveFromServerPool({'ip': mount_ipv4_string(ipv4), 'equip_name': equipament.nome, 'server_pool_identifiers': server_pool_identifiers},
                                                     'Ipv4 não pode ser disassociado do equipamento %s porque ele está sendo utilizando nos Server Pools (id:identifier) %s' % (equipament.nome, server_pool_identifiers))

                remove_ip_equipment(ip_id, equip_id, user)

                return self.response(dumps_networkapi({}))

        except IpCantRemoveFromServerPool, e:
            return self.response_error(385, e.cause.get('ip'), e.cause.get('equip_name'), e.cause.get('server_pool_identifiers'))
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:59,代码来源:IpResource.py


示例8: handle_put

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

        URL: /tipoacesso/<id_tipo_acesso>/

        """

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

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

            xml_map, attrs_map = loads(request.raw_post_data)

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

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

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

            # Verify existence
            tpa = TipoAcesso.get_by_pk(tipo_acesso_id)

            tpa.protocolo = protocol

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

            with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id):

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

            return self.response(dumps_networkapi({}))
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:59,代码来源:TipoAcessoResource.py


示例9: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para alterar a senha de um Usuario.

        URL: user-change-pass/
        """

        try:
            xml_map, attrs_map = loads(request.raw_post_data)
            self.log.info('Change user password')

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

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

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

            # Get XML data
            id_user = user_map.get('user_id')
            password = user_map.get('password')

            # 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 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', '****')

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

            with distributedlock(LOCK_USER % id_user):

                # set variable
                usr.pwd = hashlib.md5(password).hexdigest()

                try:
                    # update User
                    usr.save(user)
                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)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:58,代码来源:UsuarioChangePassResource.py


示例10: handle_put

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

        URL: environmentvip/<id_environment_vip>/
        """

        try:

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

            id_environment_vip = kwargs.get('id_environment_vip')

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

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

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

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

            with distributedlock(LOCK_ENVIRONMENT_VIP % id_environment_vip):

                # Valid Environment Vip
                environment_vip.valid_environment_vip(environmentvip_map)

                try:
                    # Update Environment Vip
                    environment_vip.save()
                except Exception, e:
                    self.log.error(u'Failed to update the environment vip.')
                    raise EnvironmentVipError(
                        e, u'Failed to update the environment vip')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:57,代码来源:EnvironmentVipResource.py


示例11: delete_dhcprelayipv6

def delete_dhcprelayipv6(user, dhcprelayipv6_id):

    dhcprelayipv6_obj = DHCPRelayIPv6.get_by_pk(id=dhcprelayipv6_id)

    with distributedlock(LOCK_NETWORK_IPV6 % dhcprelayipv6_obj.networkipv6.id):
        if not dhcprelayipv6_obj.networkipv6.active:
            dhcprelayipv6_obj.delete()
            return True
        else:
            raise exceptions.CannotRemoveDHCPRelayFromActiveNetwork()
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:10,代码来源:v1.py


示例12: handle_delete

    def handle_delete(self, request, user, *args, **kwargs):
        """Treat DELETE requests to dissociate User and Group.

        URL: usergroup/user/<id_user>/ugroup/<id_group>/dissociate/
        """

        try:

            self.log.info('Dissociate User and Group.')

            # 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')
            id_group = kwargs.get('id_group')

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

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

            # Find Group by ID to check if it exist
            UGrupo.get_by_pk(id_group)

            # Find UserGroup by ID to check if it exist
            user_group = UsuarioGrupo.get_by_user_group(id_user, id_group)

            with distributedlock(LOCK_USER_GROUP % (id_user, id_group)):

                try:

                    # remove UserGroup
                    user_group.delete()

                except Exception, e:
                    self.log.error(u'Failed to remove the UserGroup.')
                    raise GrupoError(e, u'Failed to remove the UserGroup.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:55,代码来源:UserGroupDissociateResource.py


示例13: create_lock

def create_lock(pools):
    """
    Create locks to pools list
    """
    locks_list = list()
    for pool in pools:
        lock = distributedlock(LOCK_POOL % pool['server_pool']['id'])
        lock.__enter__()
        locks_list.append(lock)

    return locks_list
开发者ID:jotagesales,项目名称:GloboNetworkAPI,代码行数:11,代码来源:facade.py


示例14: handle_delete

    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests PUT to delete Environment VIP.

        URL: environmentvip/<id_environment_vip>/
        """

        try:

            self.log.info('Delete Environment VIP')

            id_environment_vip = kwargs.get('id_environment_vip')

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

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

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

            with distributedlock(LOCK_ENVIRONMENT_VIP % id_environment_vip):

                # Find networkIPv4 by Environment VIP to check if is greater
                # than zero
                if len(NetworkIPv4.objects.filter(ambient_vip=environment_vip.id)) > 0:
                    return self.response_error(284)

                # Find networkIPv6 by Environment VIP to check if is greater
                # than zero
                if len(NetworkIPv6.objects.filter(ambient_vip=environment_vip.id)) > 0:
                    return self.response_error(285)

                try:
                    # Delete Environment Vip
                    environment_vip.delete()
                except Exception, e:
                    self.log.error(u'Failed to delete the environment vip.')
                    raise EnvironmentVipError(
                        e, u'Failed to delete the environment vip')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:52,代码来源:EnvironmentVipResource.py


示例15: handle_delete

    def handle_delete(self, request, user, *args, **kwargs):
        """
        Treat DELETE requests to remove a vip request.
        Also remove reals related and balancer ips (if this ips isn't used for another vip).

        URL: vip/delete/<id_vip>/
        """

        try:
            vip_id = kwargs.get('id_vip')
            keep_ip = bool(request.REQUEST.get('keep_ip', False))

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

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

            vip = RequisicaoVips.get_by_pk(vip_id)

            if vip.vip_criado:
                return self.response_error(370, vip_id)

            ipv4 = vip.ip
            ipv6 = vip.ipv6

            with distributedlock(LOCK_VIP % vip_id):
                try:
                    vip.delete_vips_and_reals(user)

                    vip.remove(user, vip_id)

                    # SYNC_VIP
                    delete_new(vip_id)

                    if ipv4 and not keep_ip:
                        if not self.is_ipv4_in_use(ipv4, vip_id):
                            ipv4.delete()
                    if ipv6 and not keep_ip:
                        if not self.is_ipv6_in_use(ipv6, vip_id):
                            ipv6.delete()
                except IpCantRemoveFromServerPool, e:
                    raise e
                except IpCantBeRemovedFromVip, e:
                    raise e
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:51,代码来源:RequisicaoVipDeleteResource.py


示例16: handle_put

    def handle_put(self, request, user, *args, **kwargs):
        '''Treat PUT requests to Invalidate a vlan 

        URL: vlan/<id_vlan>/invalidate/<network>
        '''

        try:

            id_vlan = kwargs.get('id_vlan')

            network = kwargs.get('network')

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

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

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

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

            with distributedlock(LOCK_VLAN % id_vlan):

                # Set Values
                if network == IP_VERSION.IPv4[0]:
                    vlan.acl_valida = 0
                    vlan.acl_file_name = None

                else:
                    vlan.acl_valida_v6 = 0
                    vlan.acl_file_name_v6 = None

                vlan.save(user)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:50,代码来源:VlanInvalidateResource.py


示例17: handle_delete

    def handle_delete(self, request, user, *args, **kwargs):
        """Trata uma requisição DELETE para excluir uma informação de acesso a equipamento

        URL: /equipamentoacesso/id_equipamento/id_tipo_acesso/ 

        """

        # Verifica acesso e obtém dados do request
        try:
            # Obtém argumentos passados na URL
            id_equipamento = kwargs.get('id_equipamento')

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

            id_tipo_acesso = kwargs.get('id_tipo_acesso')

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

            Equipamento.get_by_pk(id_equipamento)

            TipoAcesso.get_by_pk(id_tipo_acesso)

            # Após obtenção do id_equipamento podemos verificar a permissão
            if not has_perm(user,
                            AdminPermission.EQUIPMENT_MANAGEMENT,
                            AdminPermission.WRITE_OPERATION,
                            None,
                            id_equipamento,
                            AdminPermission.EQUIP_WRITE_OPERATION):
                return self.not_authorized()

            with distributedlock(LOCK_EQUIPMENT_ACCESS % id_tipo_acesso):

                # Remove a informação de acesso a equipamento
                EquipamentoAcesso.remove(user, id_equipamento, id_tipo_acesso)

                # Retorna response vazio em caso de sucesso
                return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:48,代码来源:EquipamentoAcessoResource.py


示例18: handle_put

    def handle_put(self, request, user, *args, **kwargs):
        """Trata as requisições de PUT para alterar direitos de um grupo de usuário em um grupo de equipamento.

        URL: direitosgrupoequipamento/<id_direito>/
        """
        try:
            if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

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

            try:
                xml_map, attrs_map = loads(request.raw_post_data)
                self.log.debug('XML_MAP: %s', xml_map)
            except XMLError, x:
                self.log.error(u'Erro ao ler o XML da requisicao.')
                return self.response_error(3, x)

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

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

            response = self.__valida_request(direito_map, False)
            if response is not None:
                return response

            with distributedlock(LOCK_GROUP_RIGHTS % right_id):

                DireitosGrupoEquipamento.update(user,
                                                right_id,
                                                leitura=direito_map.get(
                                                    'leitura'),
                                                escrita=direito_map.get(
                                                    'escrita'),
                                                alterar_config=direito_map.get(
                                                    'alterar_config'),
                                                exclusao=direito_map.get('exclusao'))

                return self.response(dumps_networkapi({}))
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:47,代码来源:GrupoResource.py


示例19: handle_delete

    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to remove user.

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

            self.log.info('Remove 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')

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

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

            with distributedlock(LOCK_USER % id_user):

                try:

                    if usr.eventlog_set.count() != 0:
                        raise UsuarioHasEventOrGrupoError(
                            None, u'Existe event_log associado ao usuario %s' % user.id)

                    if usr.usuariogrupo_set.count() != 0:
                        raise UsuarioHasEventOrGrupoError(
                            None, u'Existe grupo associado ao usuario %s' % user.id)

                    # remove User
                    usr.delete()

                except UsuarioHasEventOrGrupoError, e:
                    raise e
                except Exception, e:
                    self.log.error(u'Failed to remove the user.')
                    raise GrupoError(e, u'Failed to remove the user.')
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:46,代码来源:UserAlterRemoveResource.py


示例20: handle_delete

    def handle_delete(self, request, user, *args, **kwargs):
        """Treat requests DELETE to remove Equipment Script.

        URL: equipmentscript/<id_equipment>/<id_script>/
        """
        try:
            self.log.info("Remove Equipment Script")

            id_equipment = kwargs.get("id_equipment")
            id_script = kwargs.get("id_script")

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

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

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

            # Find Script by ID to check if it exist
            Roteiro.get_by_pk(id_script)

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

            with distributedlock(LOCK_EQUIPMENT_SCRIPT % id_script):

                EquipamentoRoteiro.remove(user, id_equipment, id_script)
                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:46,代码来源:EquipmentScriptRemoveResource.py



注:本文中的networkapi.distributedlock.distributedlock函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Equipamento类代码示例发布时间:2022-05-27
下一篇:
Python auth.has_perm函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap