当前位置: 首页>>代码示例>>Python>>正文


Python Equipamento.get_by_pk方法代码示例

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


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

示例1: save_rack

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
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,代码行数:35,代码来源:facade.py

示例2: handle_delete

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:61,代码来源:IpResource.py

示例3: handle_get

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:50,代码来源:ScriptGetEquipmentResource.py

示例4: handle_delete

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:50,代码来源:EquipamentoAcessoResource.py

示例5: generate_and_deploy_channel_config_sync

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
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,代码行数:32,代码来源:facade.py

示例6: deploy_config_in_equipment_synchronous

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
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,代码行数:33,代码来源:facade.py

示例7: has_perm

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
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,代码行数:35,代码来源:__init__.py

示例8: handle_delete

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:48,代码来源:EquipmentScriptRemoveResource.py

示例9: handle_get

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:60,代码来源:EnvironmentGetByEquipResource.py

示例10: handle_delete

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:38,代码来源:EquipamentoGrupoResource.py

示例11: handle_get

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:46,代码来源:GrupoEquipamentoGetByEquipResource.py

示例12: create

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:46,代码来源:models.py

示例13: handle_get

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
    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,代码行数:40,代码来源:GrupoEquipamentoRemoveAssociationEquipResource.py

示例14: update_real_pool

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
def update_real_pool(request):
    """
    - update real pool in eqpt
    - update data pool in db
    """
    pools = request.DATA.get("pools", [])
    load_balance = {}

    # valid data for save in DB and apply in eqpt
    ps, sp = valid_to_save_reals_v2(pools)

    for pool in pools:

        ids = [p['id'] for p in pool['server_pool_members'] if p['id']]
        db_members = ServerPoolMember.objects.filter(id__in=ids)
        db_members_remove = ServerPoolMember.objects.filter(server_pool__id=pool['server_pool']['id']).exclude(id__in=ids)
        db_members_id = [str(s.id) for s in db_members]

        pools_members = list()
        for pool_member in pool['server_pool_members']:

            if not pool_member['ipv6']:
                ip = pool_member['ip']['ip_formated']
            else:
                ip = pool_member['ipv6']['ip_formated']

            if pool_member['id']:
                member = db_members[db_members_id.index(str(pool_member['id']))]
                if not member.ipv6:
                    ip_db = member.ip.ip_formated
                else:
                    ip_db = member.ipv6.ip_formated

                if member.port_real == pool_member['port_real'] and ip_db == ip:
                    pools_members.append({
                        'id': pool_member['id'],
                        'ip': ip,
                        'port': pool_member['port_real'],
                        'limit': pool_member['limit'],
                        'priority': pool_member['priority'],
                        'weight': pool_member['weight'],
                    })
                else:
                    pools_members.append({
                        'id': None,
                        'ip': ip_db,
                        'port': member.port_real,
                        'remove': 1
                    })
                    pools_members.append({
                        'id': pool_member['id'],
                        'ip': ip,
                        'port': pool_member['port_real'],
                        'limit': pool_member['limit'],
                        'priority': pool_member['priority'],
                        'weight': pool_member['weight'],
                        'new': 1
                    })
            else:
                pools_members.append({
                    'id': None,
                    'ip': ip,
                    'port': pool_member['port_real'],
                    'limit': pool_member['limit'],
                    'priority': pool_member['priority'],
                    'weight': pool_member['weight'],
                    'new': 1
                })

        # members to remove
        for member in db_members_remove:
            if not member.ipv6:
                ip_db = member.ip.ip_formated
            else:
                ip_db = member.ipv6.ip_formated
            pools_members.append({
                'id': member.id,
                'ip': ip_db,
                'port': member.port_real,
                'remove': 1
            })

        # get eqpts associate with pool
        equips = EquipamentoAmbiente.objects.filter(
            ambiente__id=pool['server_pool']['environment']['id'],
            equipamento__tipo_equipamento__tipo_equipamento=u'Balanceador')

        equipment_list = [e.equipamento for e in equips]
        if all_equipments_are_in_maintenance(equipment_list):
            raise AllEquipmentsAreInMaintenanceException()

        for e in equips:
            eqpt_id = str(e.equipamento.id)
            equipment_access = EquipamentoAcesso.search(
                equipamento=e.equipamento.id,
                protocolo="https"
            ).uniqueResult()
            equipment = Equipamento.get_by_pk(e.equipamento.id)

            plugin = PluginFactory.factory(equipment)
#.........这里部分代码省略.........
开发者ID:jotagesales,项目名称:GloboNetworkAPI,代码行数:103,代码来源:facade.py

示例15: delete_real_pool

# 需要导入模块: from networkapi.equipamento.models import Equipamento [as 别名]
# 或者: from networkapi.equipamento.models.Equipamento import get_by_pk [as 别名]
def delete_real_pool(request):
    """
    delete real pool in eqpt
    """
    pools = request.DATA.get("pools", [])

    load_balance = {}

    for pool in pools:

        pools_members = []
        for pool_member in pool['server_pool_members']:
            if pool_member['ipv6'] is None:
                ip = pool_member['ip']['ip_formated']
            else:
                ip = pool_member['ipv6']['ip_formated']

            pools_members.append({
                'id': pool_member['id'],
                'ip': ip,
                'port': pool_member['port_real'],
                'member_status': pool_member['member_status'],
                'limit': pool_member['limit'],
                'priority': pool_member['priority'],
                'weight': pool_member['weight']
            })

        equips = EquipamentoAmbiente.objects.filter(
            ambiente__id=pool['server_pool']['environment']['id'],
            equipamento__tipo_equipamento__tipo_equipamento=u'Balanceador')

        equipment_list = [e.equipamento for e in equips]
        if all_equipments_are_in_maintenance(equipment_list):
            raise AllEquipmentsAreInMaintenanceException()

        for e in equips:
            eqpt_id = str(e.equipamento.id)
            equipment_access = EquipamentoAcesso.search(
                equipamento=e.equipamento.id,
                protocolo="https"
            ).uniqueResult()
            equipment = Equipamento.get_by_pk(e.equipamento.id)

            plugin = PluginFactory.factory(equipment)

            if not load_balance.get(eqpt_id):

                load_balance[eqpt_id] = {
                    'plugin': plugin,
                    'fqdn': equipment_access.fqdn,
                    'user': equipment_access.user,
                    'password': equipment_access.password,
                    'pools': [],
                }

            load_balance[eqpt_id]['pools'].append({
                'id': pool['server_pool']['id'],
                'nome': pool['server_pool']['identifier'],
                'lb_method': pool['server_pool']['lb_method'],
                'healthcheck': pool['server_pool']['healthcheck'],
                'action': pool['server_pool']['servicedownaction']['name'],
                'pools_members': pools_members
            })

    for lb in load_balance:
        load_balance[lb]['plugin'].deletePool(load_balance[lb])

    ids = [pool['server_pool']['id'] for pool in pools]
    ServerPool.objects.filter(id__in=ids).update(pool_created=False)

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


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