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

Python models.Ip类代码示例

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

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



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

示例1: handle_put

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

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

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

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

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

            Ip.get_by_pk(ip_id)

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

                ip_equipment = insert_ip_equipment(ip_id, equip_id, user)

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

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


示例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_ipv4

def create_ipv4(ipv4, user=None):
    """Creates a Ipv4."""

    try:
        ipv4_obj = Ip()
        ipv4_obj.create_v3(ipv4)
    except ObjectDoesNotExistException, e:
        raise ObjectDoesNotExistException(e.detail)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:8,代码来源:facade.py


示例4: get_ipv4_by_id

def get_ipv4_by_id(ip_id):
    """Get Ipv4."""

    try:
        network = Ip.get_by_pk(ip_id)
    except IpNotFoundError, e:
        raise ObjectDoesNotExistException(e.message)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:7,代码来源:facade.py


示例5: handle_get

    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4 by id.

        URLs: ip/get-ipv4/id_ip
        """

        try:
            # Commons Validations

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

            # Business Validations

            # Valid id access
            id_ip = kwargs.get('id_ip')

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

            # Business Rules

            ip = Ip()
            ip = ip.get_by_pk(id_ip)

            ip_map = dict()
            equip_list = []

            for ipequip in ip.ipequipamento_set.all():
                equip_list.append(ipequip.equipamento.nome)

            # IP map
            ip_map = model_to_dict(ip)
            ip_map['equipamentos'] = equip_list if len(
                equip_list) > 0 else None

            # Return XML
            return self.response(dumps_networkapi({'ipv4': ip_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:globocom,项目名称:GloboNetworkAPI,代码行数:46,代码来源:Ipv4GetByIdResource.py


示例6: get_ip_objects

def get_ip_objects(dic):
    ip_object = None
    ipv6_object = None
    if len(dic['ip']) <= 15:
        ip_object = Ip.get_by_pk(dic['id'])
    else:
        ipv6_object = Ipv6.get_by_pk(dic['id'])
    return ip_object, ipv6_object
开发者ID:jotagesales,项目名称:GloboNetworkAPI,代码行数:8,代码来源:facade.py


示例7: create

	def create(self, ipv4_id, networkipv4_id):
		ipv4 = Ip.get_by_pk(ipv4_id)
		networkipv4 = NetworkIPv4.get_by_pk(networkipv4_id)

		if len(DHCPRelayIPv4.objects.filter(ipv4=ipv4, networkipv4=networkipv4)) > 0:
			raise exceptions.DHCPRelayAlreadyExistsError(ipv4_id, networkipv4_id)
		
		self.ipv4 = ipv4
		self.networkipv4 = networkipv4
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:9,代码来源:models.py


示例8: 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


示例9: handle_get

    def handle_get(self, request, user, *args, **kwargs):
        """Treat requests GET to verify that the IP belongs to environment.

        URLs:  /ip/x1.x2.x3.x4/ambiente/<id_amb>
        URLs:  /ip/<ip>/ambiente/<id_amb>
        """

        self.log.info("GET to verify that the IP belongs to environment")

        try:

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

            environment_id = kwargs.get('id_amb')

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

            ip = kwargs.get('ip')

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

            # Find Environment by ID to check if it exist
            Ambiente.get_by_pk(environment_id)

            # Existing IP
            octs = str(IPAddress(ip, 4).exploded).split('.')
            ip = Ip.get_by_octs_and_environment(
                octs[0], octs[1], octs[2], octs[3], environment_id)

            # Build dictionary return
            ip_map = dict()
            ip_map['id'] = ip.id
            ip_map['id_vlan'] = ip.networkipv4.vlan.id
            ip_map['oct4'] = ip.oct4
            ip_map['oct3'] = ip.oct3
            ip_map['oct2'] = ip.oct2
            ip_map['oct1'] = ip.oct1
            ip_map['descricao'] = ip.descricao

            return self.response(dumps_networkapi({'ip': ip_map}))

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


示例10: buscar_ip

def buscar_ip(id_sw):

    ip_sw=None

    ips = IpEquipamento()
    ips = ips.list_by_equip(id_sw)

    for ip in ips:
        ip_sw = Ip.get_by_pk(ip.ip.id)

    if not ip_sw==None:
        ip_sw = str(ip_sw.oct1)+'.'+str(ip_sw.oct2)+'.'+str(ip_sw.oct3)+'.'+str(ip_sw.oct4)

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


示例11: handle_get

    def handle_get(self, request, user, *args, **kwargs):
        '''Handles GET requests get an IP4 available.

        URL: ip/availableip4/ip_rede
        '''

        self.log.info('Get an IP4 available')

        try:

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

            # Business Validations

            # Valid id access
            id_network = kwargs.get('id_rede')

            if not is_valid_int_greater_zero_param(id_network):
                self.log.error(
                    u'Parameter id_rede is invalid. Value: %s.', id_network)
                raise InvalidValueError(None, 'id_rede', id_network)

            # Business Rules

            ip = Ip.get_available_ip(id_network)

            list_ip = []
            list_ip.append(ip)
            network_map = dict()
            map_aux = dict()
            map_aux['ip'] = list_ip

            network_map['ip'] = map_aux

            # Business Rules

            return self.response(dumps_networkapi(network_map))

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


示例12: handle_get

    def handle_get(self, request, user, *args, **kwargs):
        '''Handles GET requests for delete an IP4 

        URL: ip4/delete/id_ip4
        '''

        self.log.info('Delete an IP4')

        try:

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

            # Business Validations

            # Valid id access
            id_ip = kwargs.get('id_ipv4')

            if not is_valid_int_greater_zero_param(id_ip):
                self.log.error(
                    u'Parameter id_ip is invalid. Value: %s.', id_ip)
                raise InvalidValueError(None, 'id_rede', id_ip)

            ip = Ip.get_by_pk(id_ip)

            with distributedlock(LOCK_IPV4 % id_ip):

                # Business Rules
                ip.delete()
                # Business Rules

                return self.response(dumps_networkapi({}))

        except IpCantBeRemovedFromVip, e:
            return self.response_error(319, "ip", 'ipv4', id_ip)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:38,代码来源:IPv4DeleteResource.py


示例13: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to edit an IP.

        URL: ipv4/edit/
        """

        self.log.info('Edit an IP')

        try:
            # 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:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            id_ip = ip_map.get('id_ip')
            description = ip_map.get('descricao')
            ip4 = ip_map.get('ip4')

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

            if not is_valid_string_maxsize(ip4, 15):
                self.log.error(u'Parameter ip4 is invalid. Value: %s.', ip4)
                raise InvalidValueError(None, 'ip4', description)

            # Valid description
            if description is not None:
                if not is_valid_string_maxsize(description, 100) or not is_valid_string_minsize(description, 3):
                    self.log.error(
                        u'Parameter description is invalid. Value: %s.', description)
                    raise InvalidValueError(None, 'description', description)

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

            # Business Rules

            # New IP

            ip = Ip()

            ip = ip.get_by_pk(id_ip)

            with distributedlock(LOCK_IPV4 % id_ip):

                # se Houver erro no ip informado para retorna-lo na mensagem
                ip_error = ip4

                # verificação se foi passado algo errado no ip
                ip4 = ip4.split('.')
                for oct in ip4:
                    if not is_valid_int_param(oct):
                        raise InvalidValueError(None, 'ip4', ip_error)

                # Ip passado de forma invalida
                if len(ip4) is not 4:
                    raise IndexError

                ip.descricao = description
                ip.oct1 = ip4[0]
                ip.oct2 = ip4[1]
                ip.oct3 = ip4[2]
                ip.oct4 = ip4[3]

                # Persist
                ip.edit_ipv4(user)

                return self.response(dumps_networkapi({}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except IndexError:
            msg = 'Invalid IP %s' % ip_error
            return self.response_error(150, msg)
        except IpNotFoundError, e:
            return self.response_error(150, e.message)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:92,代码来源:IPv4EditResource.py


示例14: handle_get

    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4.

        URLs: ip/get/id_ip
        """

        try:
            # Commons Validations

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

            # Business Validations

            # Valid id access
            id_ip = kwargs.get('id_ip')

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

            # Business Rules

            ip = Ip()

            ip = ip.get_by_pk(id_ip)

            EquipIps = []
            mapa = dict()
            #lista = []

            try:

                EquipIps = []
                equipsIp = IpEquipamento.list_by_ip(ip.id)
                for eIp in equipsIp:
                    EquipIps.append(eIp)
                mapa[ip.id] = EquipIps
                # lista.append(mapa)

            except IpEquipmentNotFoundError:
                EquipIps.append(None)
            except IpError:
                EquipIps.append(None)

            network_map = dict()

            list_ips = []
            lequips = []

            lequips = []
            ip_maps = dict()
            ip_maps['id'] = ip.id
            ip_maps['oct1'] = ip.oct1
            ip_maps['oct2'] = ip.oct2
            ip_maps['oct3'] = ip.oct3
            ip_maps['oct4'] = ip.oct4
            ip_maps['descricao'] = ip.descricao
            for equip in mapa.get(ip.id):
                equip = Equipamento.get_by_pk(equip.equipamento.id)
                lequips.append(model_to_dict(equip))
            ip_maps['equipamento'] = lequips
            list_ips.append(ip_maps)

            list_ips

            network_map['ips'] = list_ips

            # Return XML
            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,代码行数:77,代码来源:IPv4GetResource.py


示例15: handle_post


#.........这里部分代码省略.........
            if blocks != expl:
                raise InvalidValueError(None, 'rede', network)

            # Business Rules

            if version == IP_VERSION.IPv4[0]:

                # Find all networks related to environment
                nets = NetworkIPv4.objects.select_related().filter(
                    vlan__ambiente__id=vlan.ambiente.id)

                # Cast to API class
                networks = set([IPv4Network(
                    '%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets])

                # If network selected not in use
                if net in networks:
                    raise NetworkIPv4AddressNotAvailableError(
                        None, u'Unavailable address to create a NetworkIPv4.')

                if env_vip is not None:

                    # Find all networks related to environment vip
                    nets = NetworkIPv4.objects.select_related().filter(
                        ambient_vip__id=env_vip.id)

                    # Cast to API class
                    networks = set([IPv4Network(
                        '%d.%d.%d.%d/%d' % (net_ip.oct1, net_ip.oct2, net_ip.oct3, net_ip.oct4, net_ip.block)) for net_ip in nets])

                    # If there is already a network with the same  range ip as
                    # related the environment  vip
                    if net in networks:
                        raise NetworkIpAddressNotAvailableError(
                            None, u'Unavailable address to create a NetworkIPv4.')

                # # Filter case 1 - Adding new network with same ip range to another network on other environment ##
                # Get environments with networks with the same ip range
                nets = NetworkIPv4.objects.filter(
                    oct1=expl[0], oct2=expl[1], oct3=expl[2], oct4=expl[3], block=expl[4])
                env_ids = list()
                for net_ip in nets:
                    env_ids.append(net_ip.vlan.ambiente.id)

                # If other network with same ip range exists
                if len(env_ids) > 0:

                    # Get equipments related to this network's environment
                    env_equips = EquipamentoAmbiente.objects.filter(
                        ambiente=vlan.ambiente.id)

                    # Verify equipments related with all other environments
                    # that contains networks with same ip range
                    for env_id in env_ids:
                        # Equipments related to other environments
                        other_env_equips = EquipamentoAmbiente.objects.filter(
                            ambiente=env_id)
                        # Adjust to equipments
                        equip_list = list()
                        for equip_env in other_env_equips:
                            equip_list.append(equip_env.equipamento.id)

                        for env_equip in env_equips:
                            if env_equip.equipamento.id in equip_list:

                                # Filter testing
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:67,代码来源:NetworkAddResource.py


示例16: prepare_apply

def prepare_apply(load_balance, vip, created=True, user=None):

    vip_request = copy.deepcopy(vip)

    id_vip = str(vip_request.get('id'))

    equips, conf, cluster_unit = _validate_vip_to_apply(
        vip_request, created, user)

    cache_group = OptionVip.objects.get(
        id=vip_request.get('options').get('cache_group'))
    traffic_return = OptionVip.objects.get(
        id=vip_request.get('options').get('traffic_return'))
    timeout = OptionVip.objects.get(
        id=vip_request.get('options').get('timeout'))
    persistence = OptionVip.objects.get(
        id=vip_request.get('options').get('persistence'))

    if vip_request['ipv4']:
        ipv4 = Ip.get_by_pk(vip_request['ipv4']) if vip_request[
            'ipv4'] else None
        vip_request['ipv4'] = {
            'id': ipv4.id,
            'ip_formated': ipv4.ip_formated
        }

    if vip_request['ipv6']:
        ipv6 = Ipv6.get_by_pk(vip_request['ipv6']) if vip_request[
            'ipv6'] else None
        vip_request['ipv6'] = {
            'id': ipv6.id,
            'ip_formated': ipv6.ip_formated
        }

    if conf:
        conf = json.loads(conf)

    vip_request['options'] = dict()
    vip_request['options']['cache_group'] = {
        'id': cache_group.id,
        'nome_opcao_txt': cache_group.nome_opcao_txt
    }
    vip_request['options']['traffic_return'] = {
        'id': traffic_return.id,
        'nome_opcao_txt': traffic_return.nome_opcao_txt
    }
    vip_request['options']['timeout'] = {
        'id': timeout.id,
        'nome_opcao_txt': timeout.nome_opcao_txt
    }
    vip_request['options']['persistence'] = {
        'id': persistence.id,
        'nome_opcao_txt': persistence.nome_opcao_txt
    }
    vip_request['options']['cluster_unit'] = cluster_unit

    try:
        vip_request['options']['dscp'] = VipRequestDSCP.objects.get(
            vip_request=vip_request['id']
        ).dscp
    except:
        vip_request['options']['dscp'] = None
        pass

    for idx, port in enumerate(vip_request['ports']):
        for i, pl in enumerate(port['pools']):

            pool = get_pool_by_id(pl['server_pool'])
            pool_serializer = pool_slz.PoolV3Serializer(pool)

            l7_rule = OptionVip.objects.get(
                id=pl['l7_rule']).nome_opcao_txt

            healthcheck = pool_serializer.data['healthcheck']
            healthcheck['identifier'] = reserve_name_healthcheck(
                pool_serializer.data['identifier'])
            healthcheck['new'] = True
            vip_request['ports'][idx]['pools'][i]['server_pool'] = {
                'id': pool_serializer.data['id'],
                'nome': pool_serializer.data['identifier'],
                'lb_method': pool_serializer.data['lb_method'],
                'healthcheck': healthcheck,
                'action': pool_serializer.data['servicedownaction']['name'],
                'pool_created': pool_serializer.data['pool_created'],
                'pools_members': [{
                    'id': pool_member['id'],
                    'identifier': pool_member['identifier'],
                    'ip': pool_member['ip']['ip_formated'] if pool_member['ip'] else pool_member['ipv6']['ip_formated'],
                    'port': pool_member['port_real'],
                    'member_status': pool_member['member_status'],
                    'limit': pool_member['limit'],
                    'priority': pool_member['priority'],
                    'weight': pool_member['weight']
                } for pool_member in pool_serializer.data['server_pool_members']]
            }

            vip_request['ports'][idx]['pools'][i]['l7_rule'] = l7_rule
        l7_protocol = OptionVip.objects.get(
            id=port['options']['l7_protocol'])
        l4_protocol = OptionVip.objects.get(
#.........这里部分代码省略.........
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:101,代码来源:v3.py


示例17: handle_get

    def handle_get(self, request, user, *args, **kwargs):
        """Handles GET requests to get a ipv4 and ipv6 of determined Equip.

        URLs: ip/getbyequip/id_equip
        """

        try:
            # Commons Validations

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

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

            # Business Validations

            # Valid id access
            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
            listadeIps6 = []
            listaDeIps4 = []

            equip = Equipamento.get_by_pk(id_equip)

            ipEquip = IpEquipamento()
            ips = ipEquip.list_by_equip(equip.id)

            for ip4 in ips:
                listaDeIps4.append(Ip.get_by_pk(ip4.ip.id))

            ips = Ipv6Equipament.list_by_equip(equip.id)

            for ip6 in ips:
                listadeIps6.append(Ipv6.get_by_pk(ip6.ip.id))

            network_map = dict()

            list_ips = []
            list_ip4 = []
            list_ip6 = []

            dict_ips = dict()
            ip4_maps = dict()
            ip6_maps = dict()

            for ip4 in listaDeIps4:

                ip4_maps['id'] = ip4.id
                ip4_maps['oct1'] = ip4.oct1
                ip4_maps['oct2'] = ip4.oct2
                ip4_maps['oct3'] = ip4.oct3
                ip4_maps['oct4'] = ip4.oct4
                ip4_maps['descricao'] = ip4.descricao
                ip4_maps['id_rede'] = ip4.networkipv4_id
                list_ip4.append(ip4_maps)
                ip4_maps = dict()

            for ip6 in listadeIps6:

                ip6_maps['id'] = ip6.id
                ip6_maps['block1'] = ip6.block1
                ip6_maps['block2'] = ip6.block2
                ip6_maps['block3'] = ip6.block3
                ip6_maps['block4'] = ip6.block4
                ip6_maps['block5'] = ip6.block5
                ip6_maps['block6'] = ip6.block6
                ip6_maps['block7'] = ip6.block7
                ip6_maps['block8'] = ip6.block8
                ip6_maps['descricao'] = ip6.description
                ip6_maps['id_rede'] = ip6.networkipv6_id
                list_ip6.append(ip6_maps)
                ip6_maps = dict()

            dict_ips['ipv4'] = list_ip4
            dict_ips['ipv6'] = list_ip6
            list_ips.append(dict_ips)

            network_map['ips'] = list_ips

            # Return XML
            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:globocom,项目名称:GloboNetworkAPI,代码行数:96,代码来源:IPGetByEquipResource.py


示例18: insert_ip

def insert_ip(ip_map, user):
    '''Insere um IP e o relacionamento entre o IP e o equipamento.

    @param ip_map: Map com as chaves: id_equipamento, id_vlan e descricao
    @param user: Usuário autenticado na API.

    @return Em caso de erro retorna a tupla: (código da mensagem de erro, argumento01, argumento02, ...)
            Em caso de sucesso retorna a tupla: (0, <mapa com os dados do IP>)

    @raise VlanNotFoundError: VLAN não cadastrada.
    @raise VlanError: Falha ao pesquisar a VLAN. 
    @raise EquipamentoNotFoundError: Equipamento não cadastrado.
    @raise EquipamentoError: Falha ao pesquisar o Equipamento. 
    @raise IpNotAvailableError: Não existe um IP disponível para a VLAN.
    @raise IpError: Falha ao inserir no banco de dados.
    @raise UserNotAuthorizedError: Usuário sem autorização para executar a operação.  

    '''
    log = logging.getLogger('insert_ip')

    equip_id = ip_map.get('id_equipamento')
    if not is_valid_int_greater_zero_param(equip_id):
        log.error(
            u'The equip_id parameter is not a valid value: %s.', equip_id)
        raise InvalidValueError(None, 'equip_id', equip_id)
    else:
        equip_id = int(equip_id)

    if not has_perm(user,
                    AdminPermission.IPS,
                    AdminPermission.WRITE_OPERATION,
                    None,
                    equip_id,
                    AdminPermission.EQUIP_WRITE_OPERATION):
        raise UserNotAuthorizedError(
            None, u'Usuário não tem permissão para executar a operação.')

    vlan_id = ip_map.get('id_vlan')
    if not is_valid_int_greater_zero_param(vlan_id):
        log.error(u'The vlan_id parameter is not a valid value: %s.', vlan_id)
        raise InvalidValueError(None, 'vlan_id', vlan_id)
    else:
        vlan_id = int(vlan_id)

    desc_ip = ip_map.get('descricao')
    if desc_ip is not None:
        if not is_valid_string_maxsize(desc_ip, 100) or not is_valid_string_minsize(desc_ip, 3):
            log.error(u'Parameter desc_ip is invalid. Value: %s.', desc_ip)
            raise InvalidValueError(None, 'desc_ip', desc_ip)

    ip = Ip()
    ip.descricao = desc_ip

    ip.create(user, equip_id, vlan_id, False)

    ip_map = dict()
    ip_map['id'] = ip.id
    ip_map['id_redeipv4'] = ip.networkipv4.id
    ip_map['oct4'] = ip.oct4
    ip_map['oct3'] = ip.oct3
    ip_map['oct2'] = ip.oct2
    ip_map['oct1'] = ip.oct1
    ip_map['descricao'] = ip.descricao

    return 0, ip_map
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:65,代码来源:IpResource.py


示例19: handle_post


#.........这里部分代码省略.........
                    raise InvalidValueError(None, 'acl_file_v6', acl_file_v6)

                # VERIFICA SE VLAN COM MESMO ACL JA EXISTE OU NAO
                # commenting acl name check - issue #55
                # vlan.get_vlan_by_acl_v6(acl_file_v6)

            ambiente = Ambiente()
            ambiente = ambiente.get_by_pk(environment_id)

            vlan.acl_file_name = acl_file
            vlan.acl_file_name_v6 = acl_file_v6
            vlan.num_vlan = number
            vlan.nome = name
            vlan.descricao = description
            vlan.ambiente = ambiente
            vlan.ativada = 0
            vlan.acl_valida = 0
            vlan.acl_valida_v6 = 0

            vlan.insert_vlan(user)

            if network_ipv4:
                network_ipv4 = NetworkIPv4()
                vlan_map = network_ipv4.add_network_ipv4(
                    user, vlan.id, None, None, None)
                list_equip_routers_ambient = EquipamentoAmbiente.objects.select_related('equipamento').filter(
                    ambiente=vlan.ambiente.id, is_router=True)

                if list_equip_routers_ambient:

                    # Add Adds the first available ipv4 on all equipment
                    # that is configured as a router for the environment related to
                    # network
                    ip = Ip.get_first_available_ip(network_ipv4.id)

                    ip = str(ip).split('.')

                    ip_model = Ip()
                    ip_model.oct1 = ip[0]
                    ip_model.oct2 = ip[1]
                    ip_model.oct3 = ip[2]
                    ip_model.oct4 = ip[3]
                    ip_model.networkipv4_id = network_ipv4.id

                    ip_model.save(user)

                    if len(list_equip_routers_ambient) > 1 and network_ipv4.block < 30:
                        multiple_ips = True
                    else:
                        multiple_ips = False

                    for equip in list_equip_routers_ambient:
                        IpEquipamento().create(user, ip_model.id, equip.equipamento.id)

                        if multiple_ips:
                            router_ip = Ip.get_first_available_ip(
                                network_ipv4.id, True)
                            router_ip = str(router_ip).split('.')
                            ip_model2 = Ip()
                            ip_model2.oct1 = router_ip[0]
                            ip_model2.oct2 = router_ip[1]
                            ip_model2.oct3 = router_ip[2]
                            ip_model2.oct4 = router_ip[3]
                            ip_model2.networkipv4_id = network_ipv4.id
                            ip_model2.save(user)
                            IpEquipamento().create(user, ip_model2.id, equip.equipamento.id)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:67,代码来源:VlanInsertResource.py


示例20: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        '''Handles POST requests to associate and IP to an equipment.

        URL: ipv4/assoc/
        '''

        self.log.info('Associate Ip to an Equipment')

        try:
            # 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:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            ip_id = ip_map.get('id_ip')
            equip_id = ip_map.get('id_equip')
            network_ipv4_id = ip_map.get('id_net')

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

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

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

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

            # Business Rules

            # Get net
            net = NetworkIPv4.get_by_pk(network_ipv4_id)

            with distributedlock(LOCK_NETWORK_IPV4 % network_ipv4_id):

                # Get ip
                ip = Ip.get_by_pk(ip_id)
                # Get equipment
                equip = Equipamento.get_by_pk(equip_id)

                listaVlansDoEquip = []

                for ipequip in equip.ipequipamento_set.all():
                    vlan = ipequip.ip.networkipv4.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                for ipequip in equip.ipv6equipament_set.all():
                    vlan = ipequip.ip.networkipv6.vlan
                    if vlan not in listaVlansDoEquip:
                        listaVlansDoEquip.append(vlan)

                vlan_atual = net.vlan
                vlan_aux = None
                ambiente_aux = None

                for vlan in listaVlansDoEquip:
                    if vlan.num_vlan == vlan_atual.num_vlan:
                        if vlan.id != vlan_atual.id:

                     

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python factory.PluginFactory类代码示例发布时间:2022-05-27
下一篇:
Python models.Interface类代码示例发布时间: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