本文整理汇总了Python中networkapi.equipamento.models.Equipamento类的典型用法代码示例。如果您正苦于以下问题:Python Equipamento类的具体用法?Python Equipamento怎么用?Python Equipamento使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Equipamento类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_rack
def save_rack(rack_dict):
rack = Rack()
rack.nome = rack_dict.get('name')
rack.numero = rack_dict.get('number')
rack.mac_sw1 = rack_dict.get('sw1_mac')
rack.mac_sw2 = rack_dict.get('sw2_mac')
rack.mac_ilo = rack_dict.get('sw3_mac')
id_sw1 = rack_dict.get('sw1_id')
id_sw2 = rack_dict.get('sw2_id')
id_sw3 = rack_dict.get('sw3_id')
if not rack.nome:
raise exceptions.InvalidInputException("O nome do Rack não foi informado.")
if Rack.objects.filter(nome__iexact=rack.nome):
raise exceptions.RackNameDuplicatedError()
if Rack.objects.filter(numero__iexact=rack.numero):
raise exceptions.RackNumberDuplicatedValueError()
if not id_sw1:
raise exceptions.InvalidInputException("O Leaf de id %s não existe." % id_sw1)
if not id_sw2:
raise exceptions.InvalidInputException("O Leaf de id %s não existe." % id_sw2)
if not id_sw3:
raise exceptions.InvalidInputException("O OOB de id %s não existe." % id_sw3)
rack.id_sw1 = Equipamento.get_by_pk(int(id_sw1))
rack.id_sw2 = Equipamento.get_by_pk(int(id_sw2))
rack.id_ilo = Equipamento.get_by_pk(int(id_sw3))
rack.save()
return rack
示例2: 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'))
示例3: create_equipment
def create_equipment(equipments, user):
"""Create equipment"""
response = list()
try:
for equipment in equipments:
equipment_obj = Equipamento()
equipment_obj.create_v4(equipment)
response.append({'id': equipment_obj.id})
except EquipamentoError, e:
raise ValidationAPIException(e.message)
示例4: handle_get
def handle_get(self, request, user, *args, **kwargs):
"""Treat requests GET to list all the Script by Equipment.
URL: script/equipment/<id_equipment>
"""
try:
self.log.info("GET to list all the Script by Equipment")
id_equipment = kwargs.get("id_equipment")
# 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)
# Find Equipment by ID to check if it exist
Equipamento.get_by_pk(id_equipment)
# User permission
if not has_perm(
user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.READ_OPERATION,
None,
id_equipment,
AdminPermission.EQUIP_READ_OPERATION,
):
self.log.error(u"User does not have permission to perform the operation.")
raise UserNotAuthorizedError(None)
script_list = []
equipment_scripts = EquipamentoRoteiro.search(None, id_equipment)
for equipment_script in equipment_scripts:
script_map = dict()
script_map["id"] = equipment_script.roteiro.id
script_map["nome"] = equipment_script.roteiro.roteiro
script_map["descricao"] = equipment_script.roteiro.descricao
script_map["id_tipo_roteiro"] = equipment_script.roteiro.tipo_roteiro.id
script_map["nome_tipo_roteiro"] = equipment_script.roteiro.tipo_roteiro.tipo
script_map["descricao_tipo_roteiro"] = equipment_script.roteiro.tipo_roteiro.descricao
script_list.append(script_map)
return self.response(dumps_networkapi({"script": script_list}))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
示例5: 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)
示例6: generate_and_deploy_channel_config_sync
def generate_and_deploy_channel_config_sync(user, id_channel):
if not is_valid_int_greater_zero_param(id_channel):
raise exceptions.InvalidIdInterfaceException()
channel = PortChannel.get_by_pk(id_channel)
interfaces = channel.list_interfaces()
#group interfaces by equipment
equipment_interfaces = dict()
for interface in interfaces:
if interface.equipamento.id not in equipment_interfaces:
equipment_interfaces[interface.equipamento.id] = []
equipment_interfaces[interface.equipamento.id].append(interface)
files_to_deploy = {}
for equipment_id in equipment_interfaces.keys():
grouped_interfaces = equipment_interfaces[equipment_id]
file_to_deploy = _generate_config_file(grouped_interfaces)
files_to_deploy[equipment_id] = file_to_deploy
#TODO Deploy config file
#make separate threads
for equipment_id in files_to_deploy.keys():
lockvar = LOCK_INTERFACE_DEPLOY_CONFIG % (equipment_id)
equipamento = Equipamento.get_by_pk(equipment_id)
status_deploy = deploy_config_in_equipment_synchronous(files_to_deploy[equipment_id], equipamento, lockvar)
return status_deploy
示例7: has_perm
def has_perm(user, perm_function, perm_oper, egroup_id=None, equip_id=None, equip_oper=None):
"""
@raise EGrupoNotFoundError: Grupo do equipamento nao cadastrado.
@raise EquipamentoNotFoundError: Equipamento nao cadastrado.
@raise GrupoError: Falha ao pesquisar os direitos do grupo-equipamento, ou as permissões administrativas, ou o grupo do equipamento.
@raise EquipamentoError: Falha ao pesquisar o equipamento.
"""
if user is None:
return False
egroups = None
if egroup_id is not None:
egroup = EGrupo.get_by_pk(egroup_id)
egroups = [egroup]
elif equip_id is not None:
equip = Equipamento.get_by_pk(equip_id, 'grupos')
egroups = equip.grupos.all()
if len(egroups) == 0:
return False
ugroups = user.grupos.all()
for ugroup in ugroups:
try:
# perm = PermissaoAdministrativa().get_permission(perm_function, ugroup, perm_oper)
PermissaoAdministrativa().get_permission(perm_function, ugroup, perm_oper)
if (egroups is None) or (_has_equip_perm(ugroup, egroups, equip_oper)):
return True
except PermissaoAdministrativaNotFoundError:
continue
return False
示例8: 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)
示例9: aplicar
def aplicar(rack):
path_config = settings.PATH_TO_CONFIG +'*'+rack.nome+'*'
arquivos = glob.glob(path_config)
#Get all files and search for equipments of the rack
for var in arquivos:
name_equipaments = var.split('/')[-1][:-4]
for nome in name_equipaments:
#Check if file is config relative to this rack
if rack.nome in nome:
#Apply config only in spines. Leaves already have all necessary config in startup
if "ADD" in nome:
#Check if equipment in under maintenance. If so, does not aplly on it
try:
equip = Equipamento.get_by_name(nome)
if not equip.maintenance:
(erro, result) = commands.getstatusoutput("/usr/bin/backuper -T acl -b %s -e -i %s -w 300" % (var, nome))
if erro:
raise RackAplError(None, None, "Falha ao aplicar as configuracoes: %s" %(result))
except RackAplError, e:
raise e
except:
#Error equipment not found, do nothing
pass
示例10: 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)
示例11: handle_get
def handle_get(self, request, user, *args, **kwargs):
"""Treat requests GET to list all Environments.
URL: /ambiente/equip/id_equip
"""
try:
# Commons Validations
# User permission
if not has_perm(user, AdminPermission.ENVIRONMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
return self.not_authorized()
if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
return self.not_authorized()
id_equip = kwargs.get('id_equip')
if not is_valid_int_greater_zero_param(id_equip):
raise InvalidValueError(None, 'id_equip', id_equip)
# Business Rules
equip = Equipamento.get_by_pk(id_equip)
environments_list = EquipamentoAmbiente.get_by_equipment(equip.id)
# Get all environments in DB
lists_aux = []
for environment in environments_list:
env = Ambiente.get_by_pk(environment.ambiente.id)
env_map = model_to_dict(env)
env_map['grupo_l3_name'] = env.grupo_l3.nome
env_map['ambiente_logico_name'] = env.ambiente_logico.nome
env_map['divisao_dc_name'] = env.divisao_dc.nome
env_map['is_router'] = environment.is_router
try:
env_map['range'] = str(
env.min_num_vlan_1) + ' - ' + str(env.max_num_vlan_1)
if env.min_num_vlan_1 != env.min_num_vlan_2:
env_map['range'] = env_map[
'range'] + '; ' + str(env.min_num_vlan_2) + ' - ' + str(env.max_num_vlan_2)
except:
env_map['range'] = 'Nao definido'
if env.filter is not None:
env_map['filter_name'] = env.filter.name
lists_aux.append(env_map)
# Return XML
environment_list = dict()
environment_list['ambiente'] = lists_aux
return self.response(dumps_networkapi(environment_list))
except InvalidValueError, e:
self.log.error(
u'Parameter %s is invalid. Value: %s.', e.param, e.value)
return self.response_error(269, e.param, e.value)
示例12: handle_delete
def handle_delete(self, request, user, *args, **kwargs):
"""Trata as requisições de DELETE para remover uma associação entre um Equipamento e um Grupo.
URL: /equipamentogrupo/equipamento/<id_equip>/egrupo/<id_egrupo>/
"""
try:
equip_id = kwargs.get('id_equip')
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)
egroup_id = kwargs.get('id_egrupo')
if not is_valid_int_greater_zero_param(egroup_id):
self.log.error(
u'The egroup_id parameter is not a valid value: %s.', egroup_id)
raise InvalidValueError(None, 'egroup_id', egroup_id)
Equipamento.get_by_pk(equip_id)
EGrupo.get_by_pk(egroup_id)
if not has_perm(user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.WRITE_OPERATION,
None,
equip_id,
AdminPermission.EQUIP_WRITE_OPERATION):
return self.not_authorized()
with distributedlock(LOCK_EQUIPMENT_GROUP % egroup_id):
EquipamentoGrupo.remove(user, equip_id, egroup_id)
return self.response(dumps_networkapi({}))
except InvalidValueError, e:
return self.response_error(269, e.param, e.value)
示例13: handle_get
def handle_get(self, request, user, *args, **kwargs):
'''Trata as requisições de GET para listar todos os grupos de equipamento de um determindo equipamento.
URL: egrupo/equip/id_equip
'''
try:
if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.READ_OPERATION):
return self.not_authorized()
if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.READ_OPERATION):
return self.not_authorized()
id_equip = kwargs.get('id_equip')
if not is_valid_int_greater_zero_param(id_equip):
raise InvalidValueError(None, 'id_equip', id_equip)
equip = Equipamento.get_by_pk(id_equip)
egroups = EquipamentoGrupo.get_by_equipment(equip.id)
group_list = []
map_list = []
for egroup in egroups:
group_list.append(EGrupo.get_by_pk(egroup.egrupo.id))
for egroup in group_list:
egroup_map = dict()
egroup_map['id'] = egroup.id
egroup_map['nome'] = egroup.nome
map_list.append(egroup_map)
network_map = dict()
network_map['grupo'] = map_list
return self.response(dumps_networkapi(network_map))
except InvalidValueError, e:
self.log.error(
u'Parameter %s is invalid. Value: %s.', e.param, e.value)
return self.response_error(269, e.param, e.value)
示例14: create
def create(self, authenticated_user):
"""Add new interface
@return: Interface instance
@raise EquipamentoNotFoundError: Equipment doesn't exist
@raise EquipamentoError: Failed to find equipment
@raise FrontLinkNotFoundError: FrontEnd interface doesn't exist
@raise BackLinkNotFoundError: BackEnd interface doesn't exist
@raise InterfaceForEquipmentDuplicatedError: An interface with the same name on the same equipment already exists
@raise InterfaceError: Failed to add new interface
"""
# Valid equipment
self.equipamento = Equipamento.get_by_pk(self.equipamento.id)
marca = self.equipamento.modelo.marca.id if self.equipamento.tipo_equipamento.id != 2 else 0
if marca == 0:
regex = "^([a-zA-Z0-9-_/ ]+(:)?){1,6}$"
elif marca == 2:
regex = "^(Int)\s[0-9]+$"
elif marca == 3:
regex = "^(Fa|Gi|Te|Serial|Eth|mgmt)\s?[0-9]+(/[0-9]+(/[0-9]+)?)?$"
elif marca == 4:
regex = "^(interface)\s[0-9a-zA-Z]+(/[0-9a-zA-Z])+([0-9a-zA-Z-.]+)?$"
elif marca == 5:
regex = "^(eth)[0-9]+(/[0-9]+)?$"
elif marca == 8:
regex = "^[0-9]+$"
else:
regex = ""
# Checks if name is valid according to the brand
if not is_valid_regex(self.interface, regex):
raise InvalidValueError(None, 'nome', self.interface)
# Check front end interface existence
if self.ligacao_front is not None:
try:
self.ligacao_front = Interface.get_by_pk(self.ligacao_front.id)
except InterfaceNotFoundError, e:
raise FrontLinkNotFoundError(
e, u'Frontend interface does not exist')
示例15: inserir_equip
def inserir_equip(user, variablestochangecore, rede_id):
ip = Ip()
ip.descricao = None
ip.oct1, ip.oct2, ip.oct3, ip.oct4 = str(variablestochangecore["IPCORE"]).split('.')
equip = Equipamento.get_by_name(variablestochangecore["EQUIP_NAME"])
rede = NetworkIPv4.get_by_pk(rede_id)
ip.save_ipv4(equip.id, user, rede)
if ip.id is None:
raise RackAplError (None, None, "Erro ao inserir os equipamentos")
# Delete vlan's cache
destroy_cache_function([rede.vlan_id])
list_id_equip = []
list_id_equip.append(equip.id)
destroy_cache_function(list_id_equip, True)
return 0