searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

Neutron的Quota分析

2024-07-04 17:51:23
20
0

Neutron的Quota分析

以创建pool为例

一、neutron日志

image-20240412141407637.png

创建资源会先检查配额,处理逻辑在neutron.db.quota.driver.py 的 DbQuotaDriver

def _create(self, request, body, **kwargs):
        """Creates a new instance of the requested entity."""
        parent_id = kwargs.get(self._parent_id_name)
        body = Controller.prepare_request_body(request.context,
                                               body, True,
                                               self._resource, self._attr_info,
                                               allow_bulk=self._allow_bulk)
        #....
        # Quota enforcement
        reservations = []
        try:
            for (tenant, delta) in request_deltas.items():
                reservation = quota.QUOTAS.make_reservation(
                    request.context,
                    tenant,
                    {self._resource: delta},
                    self._plugin)
                reservations.append(reservation)
        except n_exc.QuotaResourceUnknown as e:
            # We don't want to quota this resource
            LOG.debug(e)

可以看到,资源是否能创建主要通过 DbQuotaDriver的 make_reservation 函数来判断

二、make_reservation

def make_reservation(self, context, tenant_id, resources, deltas, plugin):
        requested_resources = deltas.keys()
        with db_api.context_manager.writer.using(context):
            # 获取租户的资源配额
            current_limits = self.get_tenant_quotas(
                context, resources, tenant_id)
            
            # 过滤租户无配额限制的资源,即 quota < 0
            unlimited_resources = set([resource for (resource, limit) in
                                       current_limits.items() if limit < 0])
            
            # 需要计算配额的资源
            requested_resources = (set(requested_resources) -
                                   unlimited_resources)
            # 资源当前使用量
            current_usages = dict(
                (resource, resources[resource].count(
                    context, plugin, tenant_id, resync_usage=False)) for
                resource in requested_resources)
            
            # 计算资源过期的预定量
            expired_deltas = quota_api.get_reservations_for_resources(
                context, tenant_id, requested_resources, expired=True)
            # Verify that the request can be accepted with current limits
            resources_over_limit = []
            for resource in requested_resources:
                expired_reservations = expired_deltas.get(resource, 0)
                # 总使用量 = 使用量-过期预定
                total_usage = current_usages[resource] - expired_reservations
                # 可用量 = quota配额 - 总使用量
                res_headroom = current_limits[resource] - total_usage
                LOG.debug(("Attempting to reserve %(delta)d items for "
                           "resource %(resource)s. Total usage: %(total)d; "
                           "quota limit: %(limit)d; headroom:%(headroom)d"),
                          {'resource': resource,
                           'delta': deltas[resource],
                           'total': total_usage,
                           'limit': current_limits[resource],
                           'headroom': res_headroom})
                if res_headroom < deltas[resource]:
                    resources_over_limit.append(resource)
                if expired_reservations:
                    self._handle_expired_reservations(context, tenant_id)
​
            if resources_over_limit:
                raise exceptions.OverQuota(overs=sorted(resources_over_limit))
​
            return quota_api.create_reservation(
                context, tenant_id, deltas)

可以看到,整个预定资源的过程包括以下几个函数:

get_tenant_quotas:获取租户范围下的资源配额

resource.count:资源的当前使用量

get_reservations_for_resources:资源的过期预定量

create_reservation:预定资源

三、get_tenant_quotas

def get_tenant_quotas(context, resources, tenant_id):
        """Given a list of resources, retrieve the quotas for the given
        tenant. If no limits are found for the specified tenant, the operation
        returns the default limits.
        """
        
        # init with defaults
        tenant_quota = dict((key, resource.default)
                            for key, resource in resources.items())
​
        # update with tenant specific limits
        quota_objs = quota_obj.Quota.get_objects(context, project_id=tenant_id)
        for item in quota_objs:
            tenant_quota[item['resource']] = item['limit']
​
        return tenant_quota

获取租户范围下的资源配额:

  1. **首先获取资源的获取配额 resource.default,默认使用配置文件里的 **quota_+ 资源名,没有的话使用配置文件 **default_quota **与-1的较大值
def default(self):
        """Return the default value of the quota."""
        value = getattr(cfg.CONF.QUOTAS,
                        self.flag,
                        cfg.CONF.QUOTAS.default_quota)
        return max(value, -1)

image-20240412153450423.png

  1. 获取数据库中该租户的资源配额,表为 quotas
    image-20240412152630721.png

  2. 优先级数据库的配额>配置文件的配额

四、resource.count

在资源注册时,会传入count函数,除了以下几个资源是TrackedResource,其他都是CountableResource类型
image-20240412154022765.png

def _create_resource_instance(self, resource_name, plural_name):
        if (not cfg.CONF.QUOTAS.track_quota_usage or
            resource_name not in self._tracked_resource_mappings):
            LOG.info("Creating instance of CountableResource for "
                     "resource:%s", resource_name)
            return resource.CountableResource(
                resource_name, resource._count_resource,
                'quota_%s' % resource_name)
        else:
            LOG.info("Creating instance of TrackedResource for "
                     "resource:%s", resource_name)
            return resource.TrackedResource(
                resource_name,
                self._tracked_resource_mappings[resource_name],
                'quota_%s' % resource_name)

可以看到,CountableResource构造函数的第二个参数,就是资源计算使用量count的函数即 _count_resource
_count_resource 通过调用 plugin 的 get_资源名s 函数,获取该租户下的资源数量

class CountableResource(BaseResource):
    def __init__(self, name, count, flag=None, plural_name=None):
        super(CountableResource, self).__init__(
            name, flag=flag, plural_name=plural_name)
        self._count_func = count
​
    def count(self, context, plugin, tenant_id, **kwargs):
        # NOTE(ihrachys) _count_resource doesn't receive plugin
        return self._count_func(context, self.plural_name, tenant_id)
​
def _count_resource(context, collection_name, tenant_id):
    count_getter_name = "get_%s_count" % collection_name
    getter_name = "get_%s" % collection_name
​
    plugins = directory.get_plugins()
    for pname in sorted(plugins,
                        # inspect core plugin first
                        key=lambda n: n != constants.CORE):
        try:
            obj_count_getter = getattr(plugins[pname], count_getter_name)
            return obj_count_getter(
                context, filters={'tenant_id': [tenant_id]})
        except (NotImplementedError, AttributeError):
            try:
                obj_getter = getattr(plugins[pname], getter_name)
                obj_list = obj_getter(
                    context, filters={'tenant_id': [tenant_id]})
                return len(obj_list) if obj_list else 0
            except (NotImplementedError, AttributeError):
                pass
    raise NotImplementedError(
        'No plugins that support counting %s found.' % collection_name)

五、get_reservations_for_resources

获取资源的过期预定量,传入的expired为true

def get_reservations_for_resources(context, tenant_id, resources,
                                   expired=False):
    """Retrieve total amount of reservations for specified resources.
    """
    return quota_obj.Reservation.get_total_reservations_map(
        context, utcnow(), tenant_id, resources, expired)
​
​
    def get_total_reservations_map(cls, context, now, project_id,
                                   resources, expired):
        if not resources:
            return
        resv_query = context.session.query(
            models.ResourceDelta.resource,
            models.Reservation.expiration,
            sql.func.sum(models.ResourceDelta.amount)).join(
            models.Reservation)
        if expired:
            exp_expr = (models.Reservation.expiration < now)
        else:
            exp_expr = (models.Reservation.expiration >= now)
        resv_query = resv_query.filter(sa.and_(
            models.Reservation.project_id == project_id,
            models.ResourceDelta.resource.in_(resources),
            exp_expr)).group_by(
            models.ResourceDelta.resource,
            models.Reservation.expiration)
        return dict((resource, total_reserved)
                    for (resource, exp, total_reserved) in resv_query)

get_total_reservations_map 中查询了两张表,resourcedeltas和reservations。
image-20240415101246861.png

筛选出已经过期的资源预定,并统计每个资源对应的过期预定数量

六、create_reservation

  • 在创建预订时,如果发现任何过期的预订,将从数据库中删除该项目和资源的所有过期预订,从而避免过期预订的累积(在第二步的_handle_expired_reservations)。
  • 当预订提交时,已提交的资源现在存储在数据库中,会删除预订记录 commit_reservation。(资源创建成功)
  • 当取消预订(即请求未能完成)时,Neutron配额引擎只是在取消预订时删除记录 cancel_reservation,将配额使用信息标记为脏。

通过分别调用neutron.quota.QuotaEngine中的commit_reservation和cancel_reservation方法来提交或取消预订。

预订的过期时间设置为120秒,不可配置,至少目前是这样。在计算资源使用情况时,不会计算过期的预订。

# neutron/db/quota/api.py
def create_reservation(context, tenant_id, deltas, expiration=None):
    # This method is usually called from within another transaction.
    # Consider using begin_nested
    expiration = expiration or (utcnow() + datetime.timedelta(0, 120))
    delta_objs = []
    for (resource, delta) in deltas.items():
        delta_objs.append(quota_obj.ResourceDelta(
            context, resource=resource, amount=delta))
    reserv_obj = quota_obj.Reservation(
        context, project_id=tenant_id, expiration=expiration,
        resource_deltas=delta_objs)
    reserv_obj.create()
    return ReservationInfo(reserv_obj['id'],
                           reserv_obj['project_id'],
                           reserv_obj['expiration'],
                           dict((delta.resource, delta.amount)
                                for delta in reserv_obj.resource_deltas))
def commit_reservation(self, context, reservation_id):
        # Do not mark resource usage as dirty. If a reservation is committed,
        # then the relevant resources have been created. Usage data for these
        # resources has therefore already been marked dirty.
        quota_api.remove_reservation(context, reservation_id,
                                     set_dirty=False)

    def cancel_reservation(self, context, reservation_id):
        # Mark resource usage as dirty so the next time both actual resources
        # used and reserved will be recalculated
        quota_api.remove_reservation(context, reservation_id,
                                     set_dirty=True)
0条评论
作者已关闭评论
c****3
2文章数
1粉丝数
c****3
2 文章 | 1 粉丝
c****3
2文章数
1粉丝数
c****3
2 文章 | 1 粉丝
原创

Neutron的Quota分析

2024-07-04 17:51:23
20
0

Neutron的Quota分析

以创建pool为例

一、neutron日志

image-20240412141407637.png

创建资源会先检查配额,处理逻辑在neutron.db.quota.driver.py 的 DbQuotaDriver

def _create(self, request, body, **kwargs):
        """Creates a new instance of the requested entity."""
        parent_id = kwargs.get(self._parent_id_name)
        body = Controller.prepare_request_body(request.context,
                                               body, True,
                                               self._resource, self._attr_info,
                                               allow_bulk=self._allow_bulk)
        #....
        # Quota enforcement
        reservations = []
        try:
            for (tenant, delta) in request_deltas.items():
                reservation = quota.QUOTAS.make_reservation(
                    request.context,
                    tenant,
                    {self._resource: delta},
                    self._plugin)
                reservations.append(reservation)
        except n_exc.QuotaResourceUnknown as e:
            # We don't want to quota this resource
            LOG.debug(e)

可以看到,资源是否能创建主要通过 DbQuotaDriver的 make_reservation 函数来判断

二、make_reservation

def make_reservation(self, context, tenant_id, resources, deltas, plugin):
        requested_resources = deltas.keys()
        with db_api.context_manager.writer.using(context):
            # 获取租户的资源配额
            current_limits = self.get_tenant_quotas(
                context, resources, tenant_id)
            
            # 过滤租户无配额限制的资源,即 quota < 0
            unlimited_resources = set([resource for (resource, limit) in
                                       current_limits.items() if limit < 0])
            
            # 需要计算配额的资源
            requested_resources = (set(requested_resources) -
                                   unlimited_resources)
            # 资源当前使用量
            current_usages = dict(
                (resource, resources[resource].count(
                    context, plugin, tenant_id, resync_usage=False)) for
                resource in requested_resources)
            
            # 计算资源过期的预定量
            expired_deltas = quota_api.get_reservations_for_resources(
                context, tenant_id, requested_resources, expired=True)
            # Verify that the request can be accepted with current limits
            resources_over_limit = []
            for resource in requested_resources:
                expired_reservations = expired_deltas.get(resource, 0)
                # 总使用量 = 使用量-过期预定
                total_usage = current_usages[resource] - expired_reservations
                # 可用量 = quota配额 - 总使用量
                res_headroom = current_limits[resource] - total_usage
                LOG.debug(("Attempting to reserve %(delta)d items for "
                           "resource %(resource)s. Total usage: %(total)d; "
                           "quota limit: %(limit)d; headroom:%(headroom)d"),
                          {'resource': resource,
                           'delta': deltas[resource],
                           'total': total_usage,
                           'limit': current_limits[resource],
                           'headroom': res_headroom})
                if res_headroom < deltas[resource]:
                    resources_over_limit.append(resource)
                if expired_reservations:
                    self._handle_expired_reservations(context, tenant_id)
​
            if resources_over_limit:
                raise exceptions.OverQuota(overs=sorted(resources_over_limit))
​
            return quota_api.create_reservation(
                context, tenant_id, deltas)

可以看到,整个预定资源的过程包括以下几个函数:

get_tenant_quotas:获取租户范围下的资源配额

resource.count:资源的当前使用量

get_reservations_for_resources:资源的过期预定量

create_reservation:预定资源

三、get_tenant_quotas

def get_tenant_quotas(context, resources, tenant_id):
        """Given a list of resources, retrieve the quotas for the given
        tenant. If no limits are found for the specified tenant, the operation
        returns the default limits.
        """
        
        # init with defaults
        tenant_quota = dict((key, resource.default)
                            for key, resource in resources.items())
​
        # update with tenant specific limits
        quota_objs = quota_obj.Quota.get_objects(context, project_id=tenant_id)
        for item in quota_objs:
            tenant_quota[item['resource']] = item['limit']
​
        return tenant_quota

获取租户范围下的资源配额:

  1. **首先获取资源的获取配额 resource.default,默认使用配置文件里的 **quota_+ 资源名,没有的话使用配置文件 **default_quota **与-1的较大值
def default(self):
        """Return the default value of the quota."""
        value = getattr(cfg.CONF.QUOTAS,
                        self.flag,
                        cfg.CONF.QUOTAS.default_quota)
        return max(value, -1)

image-20240412153450423.png

  1. 获取数据库中该租户的资源配额,表为 quotas
    image-20240412152630721.png

  2. 优先级数据库的配额>配置文件的配额

四、resource.count

在资源注册时,会传入count函数,除了以下几个资源是TrackedResource,其他都是CountableResource类型
image-20240412154022765.png

def _create_resource_instance(self, resource_name, plural_name):
        if (not cfg.CONF.QUOTAS.track_quota_usage or
            resource_name not in self._tracked_resource_mappings):
            LOG.info("Creating instance of CountableResource for "
                     "resource:%s", resource_name)
            return resource.CountableResource(
                resource_name, resource._count_resource,
                'quota_%s' % resource_name)
        else:
            LOG.info("Creating instance of TrackedResource for "
                     "resource:%s", resource_name)
            return resource.TrackedResource(
                resource_name,
                self._tracked_resource_mappings[resource_name],
                'quota_%s' % resource_name)

可以看到,CountableResource构造函数的第二个参数,就是资源计算使用量count的函数即 _count_resource
_count_resource 通过调用 plugin 的 get_资源名s 函数,获取该租户下的资源数量

class CountableResource(BaseResource):
    def __init__(self, name, count, flag=None, plural_name=None):
        super(CountableResource, self).__init__(
            name, flag=flag, plural_name=plural_name)
        self._count_func = count
​
    def count(self, context, plugin, tenant_id, **kwargs):
        # NOTE(ihrachys) _count_resource doesn't receive plugin
        return self._count_func(context, self.plural_name, tenant_id)
​
def _count_resource(context, collection_name, tenant_id):
    count_getter_name = "get_%s_count" % collection_name
    getter_name = "get_%s" % collection_name
​
    plugins = directory.get_plugins()
    for pname in sorted(plugins,
                        # inspect core plugin first
                        key=lambda n: n != constants.CORE):
        try:
            obj_count_getter = getattr(plugins[pname], count_getter_name)
            return obj_count_getter(
                context, filters={'tenant_id': [tenant_id]})
        except (NotImplementedError, AttributeError):
            try:
                obj_getter = getattr(plugins[pname], getter_name)
                obj_list = obj_getter(
                    context, filters={'tenant_id': [tenant_id]})
                return len(obj_list) if obj_list else 0
            except (NotImplementedError, AttributeError):
                pass
    raise NotImplementedError(
        'No plugins that support counting %s found.' % collection_name)

五、get_reservations_for_resources

获取资源的过期预定量,传入的expired为true

def get_reservations_for_resources(context, tenant_id, resources,
                                   expired=False):
    """Retrieve total amount of reservations for specified resources.
    """
    return quota_obj.Reservation.get_total_reservations_map(
        context, utcnow(), tenant_id, resources, expired)
​
​
    def get_total_reservations_map(cls, context, now, project_id,
                                   resources, expired):
        if not resources:
            return
        resv_query = context.session.query(
            models.ResourceDelta.resource,
            models.Reservation.expiration,
            sql.func.sum(models.ResourceDelta.amount)).join(
            models.Reservation)
        if expired:
            exp_expr = (models.Reservation.expiration < now)
        else:
            exp_expr = (models.Reservation.expiration >= now)
        resv_query = resv_query.filter(sa.and_(
            models.Reservation.project_id == project_id,
            models.ResourceDelta.resource.in_(resources),
            exp_expr)).group_by(
            models.ResourceDelta.resource,
            models.Reservation.expiration)
        return dict((resource, total_reserved)
                    for (resource, exp, total_reserved) in resv_query)

get_total_reservations_map 中查询了两张表,resourcedeltas和reservations。
image-20240415101246861.png

筛选出已经过期的资源预定,并统计每个资源对应的过期预定数量

六、create_reservation

  • 在创建预订时,如果发现任何过期的预订,将从数据库中删除该项目和资源的所有过期预订,从而避免过期预订的累积(在第二步的_handle_expired_reservations)。
  • 当预订提交时,已提交的资源现在存储在数据库中,会删除预订记录 commit_reservation。(资源创建成功)
  • 当取消预订(即请求未能完成)时,Neutron配额引擎只是在取消预订时删除记录 cancel_reservation,将配额使用信息标记为脏。

通过分别调用neutron.quota.QuotaEngine中的commit_reservation和cancel_reservation方法来提交或取消预订。

预订的过期时间设置为120秒,不可配置,至少目前是这样。在计算资源使用情况时,不会计算过期的预订。

# neutron/db/quota/api.py
def create_reservation(context, tenant_id, deltas, expiration=None):
    # This method is usually called from within another transaction.
    # Consider using begin_nested
    expiration = expiration or (utcnow() + datetime.timedelta(0, 120))
    delta_objs = []
    for (resource, delta) in deltas.items():
        delta_objs.append(quota_obj.ResourceDelta(
            context, resource=resource, amount=delta))
    reserv_obj = quota_obj.Reservation(
        context, project_id=tenant_id, expiration=expiration,
        resource_deltas=delta_objs)
    reserv_obj.create()
    return ReservationInfo(reserv_obj['id'],
                           reserv_obj['project_id'],
                           reserv_obj['expiration'],
                           dict((delta.resource, delta.amount)
                                for delta in reserv_obj.resource_deltas))
def commit_reservation(self, context, reservation_id):
        # Do not mark resource usage as dirty. If a reservation is committed,
        # then the relevant resources have been created. Usage data for these
        # resources has therefore already been marked dirty.
        quota_api.remove_reservation(context, reservation_id,
                                     set_dirty=False)

    def cancel_reservation(self, context, reservation_id):
        # Mark resource usage as dirty so the next time both actual resources
        # used and reserved will be recalculated
        quota_api.remove_reservation(context, reservation_id,
                                     set_dirty=True)
文章来自个人专栏
文章 | 订阅
0条评论
作者已关闭评论
作者已关闭评论
2
2