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

Python models.Equipamento类代码示例

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

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



在下文中一共展示了Equipamento类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:33,代码来源:facade.py


示例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'))
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:59,代码来源:IpResource.py


示例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)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:12,代码来源:facade.py


示例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)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:48,代码来源:ScriptGetEquipmentResource.py


示例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)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:48,代码来源:EquipamentoAcessoResource.py


示例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
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:30,代码来源:facade.py


示例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
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:33,代码来源:__init__.py


示例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)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:31,代码来源:facade.py


示例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
开发者ID:itnihao,项目名称:GloboNetworkAPI,代码行数:25,代码来源:RackAplicarConfigResource.py


示例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)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:46,代码来源:EquipmentScriptRemoveResource.py


示例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)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:58,代码来源:EnvironmentGetByEquipResource.py


示例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)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:36,代码来源:EquipamentoGrupoResource.py


示例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)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:44,代码来源:GrupoEquipamentoGetByEquipResource.py


示例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')
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:44,代码来源:models.py


示例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
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:19,代码来源:RackAplicarConfigResource.py


示例16: post

    def post(self, *args, **kwargs):
        try:
            log.info('RACK deploy.')

            rack_id = kwargs.get('rack_id')
            rack = facade.get_by_pk(rack_id)

            try:
                PATH_TO_ADD_CONFIG = get_variable('path_to_add_config')
                REL_PATH_TO_ADD_CONFIG = get_variable('rel_path_to_add_config')
            except ObjectDoesNotExist:
                raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_ADD_CONFIG ou "
                                                                   "REL_PATH_TO_ADD_CONFIG.")

            path_config = PATH_TO_ADD_CONFIG + '*' + rack.nome + '*'
            arquivos = glob.glob(path_config)

            # Get all files and search for equipments of the rack
            for var in arquivos:
                filename_equipments = var.split('/')[-1]
                rel_filename = "../../" + REL_PATH_TO_ADD_CONFIG + filename_equipments
                log.debug("rel_filename: %s" % rel_filename)
                # Check if file is config relative to this rack
                if rack.nome in filename_equipments:
                    # Apply config only in spines. Leaves already have all necessary config in startup
                    if "ADD" in filename_equipments:
                        # Check if equipment in under maintenance. If so, does not aplly on it
                        equipment_name = filename_equipments.split('-ADD-')[0]
                        log.debug("equipment_name: %s" % equipment_name)
                        try:
                            equip = Equipamento.get_by_name(equipment_name)
                            if not equip.maintenance:
                                (erro, result) = commands.getstatusoutput("/usr/bin/backuper -T acl -b %s -e -i %s -w "
                                                                          "300" % (rel_filename, equipment_name))
                                log.debug("erro: %s, result: %s" % (str(erro), str(result)))
                                if erro:
                                    raise exceptions.RackAplError()
                        except exceptions.RackAplError, e:
                            raise e
                        except:
                            # Error equipment not found, do nothing
                            pass
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:42,代码来源:views.py


示例17: handle_get

    def handle_get(self, request, user, *args, **kwargs):
        '''Trata as requisições de GET remover a associação entre um grupo de equipamento e um equipamento.

        URL: egrupo/equipamento/id_equip/egrupo/id_egrupo/
        '''
        try:

            id_equip = kwargs.get('id_equipamento')
            id_egrupo = kwargs.get('id_egrupo')

            if not is_valid_int_greater_zero_param(id_egrupo):
                raise InvalidValueError(None, 'id_egrupo', id_egrupo)

            if not is_valid_int_greater_zero_param(id_equip):
                raise InvalidValueError(None, 'id_equip', id_equip)

            equip = Equipamento.get_by_pk(id_equip)
            EGrupo.get_by_pk(id_egrupo)

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

            with distributedlock(LOCK_EQUIPMENT_GROUP % id_egrupo):

                EquipamentoGrupo.remove(user, equip.id, id_egrupo)

                return self.response(dumps_networkapi({}))

        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)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:38,代码来源:GrupoEquipamentoRemoveAssociationEquipResource.py


示例18: __post_virtual_group_equipment

    def __post_virtual_group_equipment(self, equipment_maps, vip_maps, user, resp_equipment_maps, vip_equipment_ip_map):
        try:
            for equipment_map in equipment_maps:
                equipment_prefixo = equipment_map.get('prefixo')
                if equipment_prefixo is None:
                    return self.response_error(105)

                name = Equipamento.get_next_name_by_prefix(equipment_prefixo)
                equipment_map['nome'] = name

                response = insert_equipment(equipment_map, user)
                if response[0] == 0:
                    equip_id = response[2].id

                    ip_map = equipment_map.get('ip')
                    if ip_map is None:
                        return self.response_error(3, u'Não existe valor para a tag ip do equipamento %s do XML de requisição.' % equipment_map.get('nome'))

                    ip_map['id_equipamento'] = equip_id

                    response_ip = insert_ip(ip_map, user)
                    if response_ip[0] == 0:

                        # Insere um IP para cada VIP e o relacionamento dele
                        # com equipamento
                        resp_vip_maps = []
                        for vip_map in vip_maps:
                            ip_vip_map = vip_map.get('ip_real', dict())
                            ip_vip_map['id_equipamento'] = equip_id

                            response_ip_vip = insert_ip(ip_vip_map, user)
                            if (response_ip_vip[0] == 0):
                                resp_vip_maps.append({'id': vip_map.get('id'),
                                                      'ip': response_ip_vip[1]})

                                ip = str(response_ip_vip[1].get('oct1')) + '.' + str(response_ip_vip[1].get('oct2')) + '.' + str(
                                    response_ip_vip[1].get('oct3')) + '.' + str(response_ip_vip[1].get('oct4'))

                                equipment_ip_map = {
                                    'ip': ip, 'nome_equipamento': equipment_map.get('nome')}

                                equipment_ip_maps = vip_equipment_ip_map.get(
                                    vip_map.get('id'))
                                if equipment_ip_maps is None:
                                    equipment_ip_maps = [equipment_ip_map]
                                else:
                                    equipment_ip_maps.append(equipment_ip_map)

                                vip_equipment_ip_map[
                                    vip_map.get('id')] = equipment_ip_maps
                            else:
                                return self.__treat_response_error(response_ip_vip)

                        resp_equipment_maps.append({'id': equip_id,
                                                    'nome': name,
                                                    'ip': response_ip[1],
                                                    'vips': {'vip': resp_vip_maps}})

                    else:
                        return self.__treat_response_error(response_ip)
                else:
                    return self.__treat_response_error(response)

        except InvalidGroupToEquipmentTypeError:
            return self.response_error(107)
        except TipoEquipamentoNotFoundError:
            return self.response_error(100)
        except ModeloNotFoundError:
            return self.response_error(101)
        except EquipamentoNameDuplicatedError:
            return self.response_error(149)
        except EGrupoNotFoundError:
            return self.response_error(102)

        return
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:75,代码来源:GrupoVirtualResource.py


示例19: handle_post

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

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

        try:

            # Business Validations

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

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

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

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

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

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

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

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

            # Valid Equipment
            equip = Equipamento.get_by_name(name)

            # Valid EnvironmentVip
            evip = EnvironmentVip.get_by_pk(id_evip)

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

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

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

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

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

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

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:81,代码来源:RequestVipRealValidResource.py


示例20: handle_put

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

        URLs: /vip/<id_vip>/maxcon/<maxcon>/
        """

        self.log.info("Change limit connections to VIP")

        try:

            vip_id = kwargs.get('id_vip')
            maxcon = kwargs.get('maxcon')

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

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

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

            with distributedlock(LOCK_VIP % vip_id):

                vip_old = clone(vip)
                server_pools = ServerPool.objects.filter(vipporttopool__requisicao_vip=vip)
                server_pools_old = []
                server_pools_members_old = []
                for sp in server_pools:
                    server_pools_old.append(sp)
                    for spm in sp.serverpoolmember_set.all():
                        server_pools_members_old.append(spm)

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

                # Vip equipments permission
                if vip.ip is not None:
                    for ip_equipment in vip.ip.ipequipamento_set.all():
                        if not has_perm(user, AdminPermission.VIP_ALTER_SCRIPT, Admi 

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python script_utils.exec_script函数代码示例发布时间:2022-05-27
下一篇:
Python distributedlock.distributedlock函数代码示例发布时间: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