本文整理汇总了Python中networkapi.distributedlock.distributedlock函数的典型用法代码示例。如果您正苦于以下问题:Python distributedlock函数的具体用法?Python distributedlock怎么用?Python distributedlock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了distributedlock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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)
示例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
示例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)
示例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)
示例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'))
示例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({}))
示例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)
示例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)
示例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()
示例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)
示例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
示例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)
示例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