Пример #1
0
    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)
Пример #2
0
    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)
Пример #3
0
    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'))
Пример #4
0
def get_ipv4_by_id(ip_id):
    """Get Ipv4."""

    try:
        network = Ip.get_by_pk(ip_id)
    except IpNotFoundError, e:
        raise ObjectDoesNotExistException(e.message)
Пример #5
0
def _update_pool_member(members):
    """Updates pool members"""
    for member in members:
        ip = Ip.get_by_pk(member['ip']['id']) if member['ip'] else None
        ipv6 = Ipv6.get_by_pk(member['ipv6']['id']) if member['ipv6'] else None

        pool_member = ServerPoolMember.objects.get(id=member['id'])
        pool_member.ip = ip
        pool_member.ipv6 = ipv6
        pool_member.weight = member['weight']
        pool_member.priority = member['priority']
        pool_member.port_real = member['port_real']
        pool_member.member_status = member['member_status']
        pool_member.limit = member['limit']
        pool_member.save()

        if pool_member.server_pool.dscp:
            if pool_member.port_real != pool_member.server_pool.default_port:

                mb_name = '{}:{}'.format(
                    (ip.ip_formated if ip else ipv6.ip_formated),
                    member['port_real'])

                raise ValidationAPIException(
                    'DRSL3 Restriction: Pool Member {} cannot have different '
                    'port of Pool {}'.format(
                        mb_name, pool_member.server_pool.identifier))
Пример #6
0
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
Пример #7
0
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
Пример #8
0
	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
Пример #9
0
def update_vip_request(vip_request, user):
    """
    update Vip Request
    """

    vip = models.VipRequest.get_by_pk(vip_request['id'])

    vip.name = vip_request['name']
    vip.service = vip_request['service']
    vip.business = vip_request['business']
    vip.environmentvip_id = vip_request['environmentvip']
    vip.ipv4 = Ip.get_by_pk(
        vip_request['ipv4']) if vip_request['ipv4'] else None
    vip.ipv6 = Ipv6.get_by_pk(
        vip_request['ipv6']) if vip_request['ipv6'] else None

    option_ids = [
        int(option.optionvip.id)
        for option in vip.viprequestoptionvip_set.all()
    ]
    options = [
        int(vip_request['options'][key]) for key in vip_request['options']
    ]
    option_remove = list(set(option_ids) - set(options))
    option_create = list(set(options) - set(option_ids))

    vip.save()

    _update_port(vip_request['ports'], vip)

    _create_option(option_create, vip.id)
    _delete_option(option_remove, vip.id)

    dsrl3 = OptionVip.objects.filter(
        nome_opcao_txt='DSRL3', tipo_opcao='Retorno de trafego').values('id')
    if dsrl3:
        if dsrl3[0]['id'] in option_remove:
            models.VipRequestDSCP.objects.filter(vip_request=vip.id).delete()

    # perms
    groups_perm = vip_request.get('groups_permissions', [])
    groups_perm += facade_usr.get_groups(
        vip_request.get('users_permissions', []))
    groups = facade_usr.reduce_groups(groups_perm)

    perm = vip_request.get('permissions')
    perm_replace = perm.get('replace') if perm else False

    update_groups_permissions(groups, vip.id, user, perm_replace)

    # sync with old tables
    syncs.new_to_old(vip)
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
Пример #11
0
def _create_pool_member(members, pool):
    """Creates pool members"""
    for member in members:
        ip = Ip.get_by_pk(member['ip']['id']) if member['ip'] else None
        ipv6 = Ipv6.get_by_pk(member['ipv6']['id']) if member['ipv6'] else None
        identifier = ip.ip_formated if ip else ipv6.ip_formated

        pool_member = ServerPoolMember()
        pool_member.server_pool = pool
        pool_member.ip = ip
        pool_member.ipv6 = ipv6
        pool_member.identifier = identifier
        pool_member.weight = member['weight']
        pool_member.priority = member['priority']
        pool_member.port_real = member['port_real']
        pool_member.member_status = member['member_status']
        pool_member.limit = member['limit']
        pool_member.save()

        # vip with dsrl3 using pool
        if pool.dscp:

            mbs = pool_member.get_spm_by_eqpt_id(pool_member.equipment.id)

            # check all the pools related to this pool vip request to filter
            # dscp value
            related_viprequestports = pool.vips[0].viprequestport_set.all()
            vippools = [
                p.viprequestportpool_set.all()[0].server_pool_id
                for p in related_viprequestports
            ]

            sps = ServerPool.objects.filter(serverpoolmember__in=mbs).exclude(
                id__in=vippools)
            dscps = [sp.dscp for sp in sps]

            mb_name = '{}:{}'.format(
                (ip.ip_formated if ip else ipv6.ip_formated),
                member['port_real'])
            if pool.dscp in dscps:
                raise ValidationAPIException(
                    'DRSL3 Restriction: Pool Member {} cannot be insert'
                    ' in Pool {}, because already in other pool'.format(
                        mb_name, pool.identifier))

            if pool_member.port_real != pool.default_port:
                raise ValidationAPIException(
                    'DRSL3 Restriction: Pool Member {} cannot have different'
                    ' port of Pool {}'.format(mb_name, pool.identifier))
    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)
    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)
Пример #14
0
    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)
Пример #15
0
def create_vip_request(vip_request, user):
    """
    Create Vip Request
    """
    # Remove when RequisicaoVips is die
    req = RequisicaoVips()
    req.save()

    vip = models.VipRequest()
    vip.id = req.id
    vip.name = vip_request['name']
    vip.service = vip_request['service']
    vip.business = vip_request['business']
    vip.environmentvip_id = vip_request['environmentvip']
    vip.ipv4 = Ip.get_by_pk(
        vip_request['ipv4']) if vip_request['ipv4'] else None
    vip.ipv6 = Ipv6.get_by_pk(
        vip_request['ipv6']) if vip_request['ipv6'] else None

    option_create = [
        vip_request['options'][key] for key in vip_request['options']
    ]
    vip.save()

    _create_port(vip_request['ports'], vip)
    _create_option(option_create, vip.id)

    # perms
    groups_perm = vip_request.get('groups_permissions', [])
    groups_perm += facade_usr.get_groups(
        vip_request.get('users_permissions', []))
    groups = facade_usr.reduce_groups(groups_perm)
    create_groups_permissions(groups, vip.id, user)

    # sync with old tables
    syncs.new_to_old(vip)

    return vip
    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)
    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)
Пример #18
0
    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)
    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)
Пример #20
0
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=port['options']['l4_protocol'])

        vip_request['ports'][idx]['options'] = dict()
        vip_request['ports'][idx]['options']['l7_protocol'] = {
            'id': l7_protocol.id,
            'nome_opcao_txt': l7_protocol.nome_opcao_txt
        }
        vip_request['ports'][idx]['options']['l4_protocol'] = {
            'id': l4_protocol.id,
            'nome_opcao_txt': l4_protocol.nome_opcao_txt
        }

    vip_request['conf'] = conf

    if conf:
        for idx, layer in enumerate(conf['conf']['layers']):
            requiments = layer.get('requiments')
            if requiments:
                # validate for port
                for idx_port, port in enumerate(vip['ports']):
                    for requiment in requiments:
                        condicionals = requiment.get('condicionals')
                        for condicional in condicionals:

                            validated = True

                            validations = condicional.get('validations')
                            for validation in validations:
                                if validation.get('type') == 'optionvip':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        int(vip['options'][validation.get(
                                            'variable')]),
                                        int(validation.get('value')))

                                if validation.get('type') == 'portoptionvip':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        int(port['options'][validation.get(
                                            'variable')]),
                                        int(validation.get('value')))

                                if validation.get(
                                        'type') == 'field' and validation.get(
                                            'variable') == 'cluster_unit':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        cluster_unit, validation.get('value'))
                            if validated:
                                use = condicional.get('use')
                                for item in use:
                                    definitions = item.get('definitions')
                                    eqpts = item.get('eqpts')
                                    if eqpts:

                                        eqpts = Equipamento.objects.filter(
                                            id__in=eqpts,
                                            maintenance=0,
                                            tipo_equipamento__tipo_equipamento=
                                            u'Balanceador').distinct()

                                        if facade_eqpt.all_equipments_are_in_maintenance(
                                                equips):
                                            raise exceptions_eqpt.AllEquipmentsAreInMaintenanceException(
                                            )

                                        if user:
                                            if not facade_eqpt.all_equipments_can_update_config(
                                                    equips, user):
                                                raise exceptions_eqpt.UserDoesNotHavePermInAllEqptException(
                                                    'User does not have permission to update conf in eqpt. \
                                                    Verify the permissions of user group with equipment group. Vip:{}'
                                                    .format(vip_request['id']))

                                        for eqpt in eqpts:
                                            eqpt_id = str(eqpt.id)

                                            if not load_balance.get(eqpt_id):
                                                equipment_access = EquipamentoAcesso.search(
                                                    equipamento=eqpt.id)

                                                plugin = PluginFactory.factory(
                                                    eqpt)

                                                load_balance[eqpt_id] = {
                                                    'plugin': plugin,
                                                    'access': equipment_access,
                                                    'vips': [],
                                                    'layers': {},
                                                }

                                            idx_layer = str(idx)
                                            idx_port_str = str(port['port'])
                                            if not load_balance[eqpt_id][
                                                    'layers'].get(id_vip):
                                                load_balance[eqpt_id][
                                                    'layers'][id_vip] = dict()

                                            if load_balance[eqpt_id]['layers'][
                                                    id_vip].get(idx_layer):
                                                if load_balance[eqpt_id][
                                                        'layers'][id_vip].get(
                                                            idx_layer).get(
                                                                'definitions'
                                                            ).get(
                                                                idx_port_str):
                                                    load_balance[eqpt_id][
                                                        'layers'][id_vip][
                                                            idx_layer][
                                                                'definitions'][
                                                                    idx_port_str] += definitions
                                                else:
                                                    load_balance[eqpt_id][
                                                        'layers'][id_vip][
                                                            idx_layer][
                                                                'definitions'][
                                                                    idx_port_str] = definitions
                                            else:
                                                load_balance[eqpt_id][
                                                    'layers'][id_vip][
                                                        idx_layer] = {
                                                            'vip_request':
                                                            vip_request,
                                                            'definitions': {
                                                                idx_port_str:
                                                                definitions
                                                            }
                                                        }
                                # In first validated==True stops conditionals.
                                # Removing this break will add a wrong
                                # conditional.
                                break

    for e in equips:
        eqpt_id = str(e.id)

        if not load_balance.get(eqpt_id):

            equipment_access = EquipamentoAcesso.search(equipamento=e.id)

            plugin = PluginFactory.factory(e)

            load_balance[eqpt_id] = {
                'plugin': plugin,
                'access': equipment_access,
                'vips': [],
                'layers': {},
            }

        load_balance[eqpt_id]['vips'].append({'vip_request': vip_request})

    return load_balance
Пример #21
0
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=port['options']['l4_protocol'])

        vip_request['ports'][idx]['options'] = dict()
        vip_request['ports'][idx]['options']['l7_protocol'] = {
            'id': l7_protocol.id,
            'nome_opcao_txt': l7_protocol.nome_opcao_txt
        }
        vip_request['ports'][idx]['options']['l4_protocol'] = {
            'id': l4_protocol.id,
            'nome_opcao_txt': l4_protocol.nome_opcao_txt
        }

    vip_request['conf'] = conf

    if conf:
        for idx, layer in enumerate(conf['conf']['layers']):
            requiments = layer.get('requiments')
            if requiments:
                # validate for port
                for idx_port, port in enumerate(vip['ports']):
                    for requiment in requiments:
                        condicionals = requiment.get('condicionals')
                        for condicional in condicionals:

                            validated = True

                            validations = condicional.get('validations')
                            for validation in validations:
                                if validation.get('type') == 'optionvip':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        int(vip['options'][
                                            validation.get('variable')]),
                                        int(validation.get('value'))
                                    )

                                if validation.get('type') == 'portoptionvip':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        int(port['options'][
                                            validation.get('variable')]),
                                        int(validation.get('value'))
                                    )

                                if validation.get('type') == 'field' and validation.get('variable') == 'cluster_unit':
                                    validated &= valid_expression(
                                        validation.get('operator'),
                                        cluster_unit,
                                        validation.get('value')
                                    )
                            if validated:
                                use = condicional.get('use')
                                for item in use:
                                    definitions = item.get('definitions')
                                    eqpts = item.get('eqpts')
                                    if eqpts:

                                        eqpts = Equipamento.objects.filter(
                                            id__in=eqpts,
                                            maintenance=0,
                                            tipo_equipamento__tipo_equipamento=u'Balanceador').distinct()

                                        if facade_eqpt.all_equipments_are_in_maintenance(equips):
                                            raise exceptions_eqpt.AllEquipmentsAreInMaintenanceException()

                                        if user:
                                            if not facade_eqpt.all_equipments_can_update_config(equips, user):
                                                raise exceptions_eqpt.UserDoesNotHavePermInAllEqptException(
                                                    'User does not have permission to update conf in eqpt. \
                                                    Verify the permissions of user group with equipment group. Vip:{}'.format(
                                                        vip_request['id']))

                                        for eqpt in eqpts:
                                            eqpt_id = str(eqpt.id)

                                            if not load_balance.get(eqpt_id):
                                                equipment_access = EquipamentoAcesso.search(
                                                    equipamento=eqpt.id
                                                )

                                                plugin = PluginFactory.factory(
                                                    eqpt)

                                                load_balance[eqpt_id] = {
                                                    'plugin': plugin,
                                                    'access': equipment_access,
                                                    'vips': [],
                                                    'layers': {},
                                                }

                                            idx_layer = str(idx)
                                            idx_port_str = str(port['port'])
                                            if not load_balance[eqpt_id]['layers'].get(id_vip):
                                                load_balance[eqpt_id][
                                                    'layers'][id_vip] = dict()

                                            if load_balance[eqpt_id]['layers'][id_vip].get(idx_layer):
                                                if load_balance[eqpt_id]['layers'][id_vip].get(idx_layer).get('definitions').get(idx_port_str):
                                                    load_balance[eqpt_id]['layers'][id_vip][idx_layer][
                                                        'definitions'][idx_port_str] += definitions
                                                else:
                                                    load_balance[eqpt_id]['layers'][id_vip][idx_layer][
                                                        'definitions'][idx_port_str] = definitions
                                            else:
                                                load_balance[eqpt_id]['layers'][id_vip][idx_layer] = {
                                                    'vip_request': vip_request,
                                                    'definitions': {
                                                        idx_port_str: definitions
                                                    }
                                                }
                                # In first validated==True stops conditionals.
                                # Removing this break will add a wrong
                                # conditional.
                                break

    for e in equips:
        eqpt_id = str(e.id)

        if not load_balance.get(eqpt_id):

            equipment_access = EquipamentoAcesso.search(
                equipamento=e.id
            )

            plugin = PluginFactory.factory(e)

            load_balance[eqpt_id] = {
                'plugin': plugin,
                'access': equipment_access,
                'vips': [],
                'layers': {},
            }

        load_balance[eqpt_id]['vips'].append({'vip_request': vip_request})

    return load_balance
    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)
Пример #23
0
    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)
    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:

                            # Filter case 3 - Vlans with same number cannot
                            # share equipments ##

                            flag_vlan_error = False
                            # Filter testing
                            if vlan.ambiente.filter is None or vlan_atual.ambiente.filter is None:
                                flag_vlan_error = True
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan_atual.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(filter=vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                #Equipment type should be in both filters
                                if equip.tipo_equipamento not in tp_equip_list_one or equip.tipo_equipamento not in tp_equip_list_two:
                                    flag_vlan_error = True

                                    #Out of band network is never trunked, it is only in mgmt interface
                                    # allow it - not a good thing to to, but is very specific
                                    if vlan.ambiente.divisao_dc.nome == 'OOB-CM' or vlan_atual.ambiente.divisao_dc.nome == 'OOB-CM':
                                        flag_vlan_error = False
                                        

                            ## Filter case 3 - end ##

                            if flag_vlan_error:
                                ambiente_aux = vlan.ambiente
                                vlan_aux = vlan
                                nome_ambiente = "%s - %s - %s" % (
                                    vlan.ambiente.divisao_dc.nome, vlan.ambiente.ambiente_logico.nome, vlan.ambiente.grupo_l3.nome)
                                raise VlanNumberNotAvailableError(None,
                                                                  '''O ip informado não pode ser cadastrado, pois o equipamento %s, faz parte do ambiente %s (id %s), 
                                                                    que possui a Vlan de id %s, que também possui o número %s, e não é permitido que vlans que compartilhem o mesmo ambiente 
                                                                    por meio de equipamentos, possuam o mesmo número, edite o número de uma das Vlans ou adicione um filtro no ambiente para efetuar o cadastro desse IP no Equipamento Informado.
                                                                    ''' % (equip.nome, nome_ambiente, ambiente_aux.id, vlan_aux.id, vlan_atual.num_vlan))

                # Persist
                try:

                    try:
                        ipEquip = IpEquipamento()
                        ipEquip.get_by_ip_equipment(ip.id, equip_id)

                        # Ip %s.%s.%s.%s already has association with
                        # Equipament %s.' % (self.oct1, self.oct2, self.oct3,
                        # self.oct4,equipment_id)
                        raise IpEquipmentAlreadyAssociation(None, u'Ip %s.%s.%s.%s already has association with Equipament %s.' % (
                            ip.oct1, ip.oct2, ip.oct3, ip.oct4, equip_id))
                    except IpEquipmentNotFoundError, e:
                        pass

                    equipment = Equipamento().get_by_pk(equip_id)
                    ip_equipment = IpEquipamento()
                    ip_equipment.ip = ip

                    ip_equipment.equipamento = equipment

                    # Filter case 2 - Adding new IpEquip for a equip that
                    # already have ip in other network with the same range ##

                    # Get all IpEquipamento related to this equipment
                    ip_equips = IpEquipamento.objects.filter(
                        equipamento=equip_id)

                    for ip_test in [ip_equip.ip for ip_equip in ip_equips]:
                        if ip_test.networkipv4.oct1 == ip.networkipv4.oct1 and \
                                ip_test.networkipv4.oct2 == ip.networkipv4.oct2 and \
                                ip_test.networkipv4.oct3 == ip.networkipv4.oct3 and \
                                ip_test.networkipv4.oct4 == ip.networkipv4.oct4 and \
                                ip_test.networkipv4.block == ip.networkipv4.block and \
                                ip_test.networkipv4 != ip.networkipv4:

                            # Filter testing
                            if ip_test.networkipv4.vlan.ambiente.filter is None or ip.networkipv4.vlan.ambiente.filter is None:
                                raise IpRangeAlreadyAssociation(
                                    None, u'Equipment is already associated with another ip with the same ip range.')
                            else:
                                # Test both environment's filters
                                tp_equip_list_one = list()
                                for fet in FilterEquipType.objects.filter(filter=ip.networkipv4.vlan.ambiente.filter.id):
                                    tp_equip_list_one.append(fet.equiptype)

                                tp_equip_list_two = list()
                                for fet in FilterEquipType.objects.filter(filter=ip_test.networkipv4.vlan.ambiente.filter.id):
                                    tp_equip_list_two.append(fet.equiptype)

                                if equipment.tipo_equipamento not in tp_equip_list_one or equipment.tipo_equipamento not in tp_equip_list_two:
                                    raise IpRangeAlreadyAssociation(
                                        None, u'Equipment is already associated with another ip with the same ip range.')

                    ## Filter case 2 - end ##

                    ip_equipment.save()

                    # Makes Environment Equipment association
                    try:
                        equipment_environment = EquipamentoAmbiente()
                        equipment_environment.equipamento = equipment
                        equipment_environment.ambiente = net.vlan.ambiente
                        equipment_environment.create(user)

                        # Delete vlan's cache
                        destroy_cache_function([net.vlan_id])
                    except EquipamentoAmbienteDuplicatedError, e:
                        # If already exists, OK !
                        pass

                except IpRangeAlreadyAssociation, e:
                    raise IpRangeAlreadyAssociation(None, e.message)
Пример #25
0
def save_server_pool_member(user, sp, list_server_pool_member):

    list_pool_member = list()
    old_priorities_list = list()
    # Remove empty values from list
    id_pool_member_noempty = [x['id_pool_member'] for x in list_server_pool_member if x['id_pool_member'] != '']

    #exclue server pool member
    del_smp = sp.serverpoolmember_set.exclude(id__in=id_pool_member_noempty)
    if del_smp:
        for obj in del_smp:

            obj.delete(user)

            #execute script remove real if pool already created
            #commit transaction after each successful script call
            if sp.pool_created:
                command = settings.POOL_REAL_REMOVE % (obj.server_pool_id, obj.ip_id if obj.ip else obj.ipv6_id, obj.port_real)
                code, _, _ = exec_script(command)
                if code != 0:
                    raise exceptions.ScriptCreatePoolException()
                transaction.commit()

    if list_server_pool_member:
        apply_new_priorities = False
        for dic in list_server_pool_member:
        #
            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'])

            id_pool = sp.id
            id_ip = ip_object and ip_object.id or ipv6_object and ipv6_object.id
            port_ip = dic['port_real']

            if dic['id_pool_member']:
                spm = ServerPoolMember.objects.get(id=dic['id_pool_member'])
                spm.server_pool = sp
                spm.identifier = dic['nome_equips']
                spm.ip = ip_object
                spm.ipv6 = ipv6_object
                spm.weight = dic['weight']
                spm.limit = sp.default_limit
                old_spm_priority = spm.priority
                old_priorities_list.append(old_spm_priority)
                spm.priority = dic['priority']
                spm.port_real = dic['port_real']
                spm.save(user)
                if(old_spm_priority != spm.priority and sp.pool_created):
                    apply_new_priorities = True
            else:
                spm = ServerPoolMember(server_pool=sp, identifier=dic['nome_equips'], ip=ip_object, ipv6=ipv6_object,
                                       priority=dic['priority'], weight=dic['weight'], limit=sp.default_limit,
                                       port_real=dic['port_real'])
                spm.save(user)

                old_priorities_list.append(dic['priority'])

                #execute script to create real if pool already created
                #commits transaction. Rolls back if script returns error
                if sp.pool_created:
                    transaction.commit()
                    #def prepare_and_save(self, server_pool, ip, ip_type, priority, weight, port_real, user, commit=False):
                    #spm.prepare_and_save(sp, ip_object, IP_VERSION.IPv4[1], dic['priority'], dic['weight'], dic['port_real'], user, True)
                    command = settings.POOL_REAL_CREATE % (id_pool, id_ip, port_ip)
                    code, _, _ = exec_script(command)
                    if code != 0:
                        spm.delete(user)
                        transaction.commit()
                        raise exceptions.ScriptCreatePoolException()

                #if sp.healthcheck_id:
                #    spm.healthcheck = sp.healthcheck
            list_pool_member.append(spm)

        #Applies new priority in pool - only 1 script run for all members
        if(apply_new_priorities):
            transaction.commit()
            command = settings.POOL_MEMBER_PRIORITIES % (sp.id)
            code, _, _ = exec_script(command)
            if code != 0:
                for i in len(old_priorities_list):
                    list_pool_member[i].priority = old_priorities_list[i]
                    list_pool_member[i].save(user)
                transaction.commit()
                raise exceptions.ScriptAlterPriorityPoolMembersException()

    return list_pool_member
Пример #26
0
    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)
Пример #27
0
    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'))