|
| 1 | +# Copyright 2026 Genesis Corporation. |
| 2 | +# |
| 3 | +# All Rights Reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 6 | +# not use this file except in compliance with the License. You may obtain |
| 7 | +# a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 13 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 14 | +# License for the specific language governing permissions and limitations |
| 15 | +# under the License. |
| 16 | + |
| 17 | +import importlib |
| 18 | +import logging |
| 19 | +import typing as tp |
| 20 | +import uuid as sys_uuid |
| 21 | + |
| 22 | +from restalchemy.common import exceptions as ra_e |
| 23 | +from restalchemy.dm import filters as dm_filters |
| 24 | +from restalchemy.dm import models |
| 25 | +from restalchemy.dm import properties |
| 26 | +from restalchemy.dm import types |
| 27 | +from restalchemy.storage.sql import orm |
| 28 | + |
| 29 | +LOG = logging.getLogger(__name__) |
| 30 | + |
| 31 | + |
| 32 | +class QuotaExceededError(ra_e.ValidationErrorException): |
| 33 | + message = "Quota exceeded for resource '%(resource_name)s' in project %(project_id)s: %(current)s > %(limit)s" |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, resource_name: str, limit: int, current: int, project_id: sys_uuid.UUID |
| 37 | + ): |
| 38 | + super().__init__( |
| 39 | + resource_name=resource_name, |
| 40 | + limit=limit, |
| 41 | + current=current, |
| 42 | + project_id=project_id, |
| 43 | + ) |
| 44 | + self.resource_name = resource_name |
| 45 | + self.limit = limit |
| 46 | + self.current = current |
| 47 | + self.project_id = project_id |
| 48 | + |
| 49 | + |
| 50 | +DEFAULT_QUOTA_LIMIT = 1000 |
| 51 | +DEFAULT_QUOTA_LIMITS: tp.Dict[str, int] = { |
| 52 | + "net_lb": DEFAULT_QUOTA_LIMIT, |
| 53 | + "compute_sets": DEFAULT_QUOTA_LIMIT, |
| 54 | + "nodes": DEFAULT_QUOTA_LIMIT, |
| 55 | + "secret_passwords": DEFAULT_QUOTA_LIMIT, |
| 56 | + "secret_certificates": DEFAULT_QUOTA_LIMIT, |
| 57 | + "secret_rsa_keys": DEFAULT_QUOTA_LIMIT, |
| 58 | + "secret_ssh_keys": DEFAULT_QUOTA_LIMIT, |
| 59 | +} |
| 60 | +DEFAULT_QUOTA_FIELD_LIMITS: tp.Dict[str, tp.Dict[str, int]] = { |
| 61 | + "nodes": {"cores": 10000}, |
| 62 | +} |
| 63 | +QUOTA_RESOURCE_MODELS = { |
| 64 | + "net_lb": "exordos_core.user_api.network.dm.models:LB", |
| 65 | + "compute_sets": "exordos_core.compute.dm.models:NodeSet", |
| 66 | + "nodes": "exordos_core.compute.dm.models:Node", |
| 67 | + "secret_passwords": "exordos_core.secret.dm.models:Password", |
| 68 | + "secret_certificates": "exordos_core.secret.dm.models:Certificate", |
| 69 | + "secret_rsa_keys": "exordos_core.secret.dm.models:RSAKey", |
| 70 | + "secret_ssh_keys": "exordos_core.secret.dm.models:SSHKey", |
| 71 | +} |
| 72 | + |
| 73 | + |
| 74 | +def get_quota_resource_model(resource_name: str) -> type: |
| 75 | + try: |
| 76 | + module_name, class_name = QUOTA_RESOURCE_MODELS[resource_name].split(":") |
| 77 | + except KeyError: |
| 78 | + raise ValueError(f"Unknown quota resource: {resource_name}") |
| 79 | + |
| 80 | + module = importlib.import_module(module_name) |
| 81 | + return getattr(module, class_name) |
| 82 | + |
| 83 | + |
| 84 | +class QuotaModelMixin: |
| 85 | + def _quota_limits(self, session) -> tp.Collection["QuotaLimit"]: |
| 86 | + limits = list( |
| 87 | + QuotaLimit.objects.get_all( |
| 88 | + session=session, |
| 89 | + filters={ |
| 90 | + "project_id": dm_filters.EQ(self.project_id), |
| 91 | + "resource_name": dm_filters.EQ(self.__tablename__), |
| 92 | + }, |
| 93 | + ) |
| 94 | + ) |
| 95 | + limit_fields = {limit.field_name for limit in limits} |
| 96 | + if "" not in limit_fields: |
| 97 | + default_limit = DEFAULT_QUOTA_LIMITS.get(self.__tablename__) |
| 98 | + if default_limit is not None: |
| 99 | + limits.append( |
| 100 | + QuotaLimit( |
| 101 | + project_id=self.project_id, |
| 102 | + resource_name=self.__tablename__, |
| 103 | + field_name="", |
| 104 | + limit=default_limit, |
| 105 | + ) |
| 106 | + ) |
| 107 | + |
| 108 | + for field_name, default_limit in DEFAULT_QUOTA_FIELD_LIMITS.get( |
| 109 | + self.__tablename__, {} |
| 110 | + ).items(): |
| 111 | + if field_name not in limit_fields: |
| 112 | + limits.append( |
| 113 | + QuotaLimit( |
| 114 | + project_id=self.project_id, |
| 115 | + resource_name=self.__tablename__, |
| 116 | + field_name=field_name, |
| 117 | + limit=default_limit, |
| 118 | + ) |
| 119 | + ) |
| 120 | + return limits |
| 121 | + |
| 122 | + def _quota_check(self, session) -> None: |
| 123 | + # Check entity-count and aggregate-field limits before inserting. |
| 124 | + try: |
| 125 | + limits = self._quota_limits(session) |
| 126 | + except ValueError: |
| 127 | + LOG.exception("Invalid quota configuration for %s", self.__tablename__) |
| 128 | + return |
| 129 | + |
| 130 | + if not limits: |
| 131 | + return |
| 132 | + |
| 133 | + field_limits = [limit for limit in limits if limit.field_name] |
| 134 | + count_limits = [limit for limit in limits if not limit.field_name] |
| 135 | + aggregate_fields = ", ".join( |
| 136 | + f"SUM({field_name}) AS {field_name}" |
| 137 | + for field_name in sorted({limit.field_name for limit in field_limits}) |
| 138 | + ) |
| 139 | + selected_fields = ", ".join( |
| 140 | + field |
| 141 | + for field in ("COUNT(uuid) AS entity_count", aggregate_fields) |
| 142 | + if field |
| 143 | + ) |
| 144 | + result = session.execute( |
| 145 | + f"SELECT {selected_fields} FROM {self.__tablename__} WHERE project_id = %s", |
| 146 | + (self.project_id,), |
| 147 | + ) |
| 148 | + row = result.fetchone() |
| 149 | + |
| 150 | + for quota_limit in field_limits: |
| 151 | + current = (row[quota_limit.field_name] or 0) + getattr( |
| 152 | + self, quota_limit.field_name |
| 153 | + ) |
| 154 | + if current > quota_limit.limit: |
| 155 | + raise QuotaExceededError( |
| 156 | + resource_name=f"{self.__tablename__}.{quota_limit.field_name}", |
| 157 | + limit=quota_limit.limit, |
| 158 | + current=current, |
| 159 | + project_id=self.project_id, |
| 160 | + ) |
| 161 | + |
| 162 | + current_count = row["entity_count"] + 1 |
| 163 | + for quota_limit in count_limits: |
| 164 | + if current_count > quota_limit.limit: |
| 165 | + raise QuotaExceededError( |
| 166 | + resource_name=self.__tablename__, |
| 167 | + limit=quota_limit.limit, |
| 168 | + current=current_count, |
| 169 | + project_id=self.project_id, |
| 170 | + ) |
| 171 | + |
| 172 | + def insert(self, session=None): |
| 173 | + # Reserve quota capacity by checking entity-count and field totals. |
| 174 | + if session is None: |
| 175 | + with self._get_engine().session_manager(session=session) as s: |
| 176 | + self._quota_check(s) |
| 177 | + super().insert(session=s) |
| 178 | + else: |
| 179 | + self._quota_check(session) |
| 180 | + super().insert(session=session) |
| 181 | + |
| 182 | + |
| 183 | +class QuotaLimit( |
| 184 | + models.ModelWithUUID, |
| 185 | + models.ModelWithTimestamp, |
| 186 | + models.ModelWithProject, |
| 187 | + orm.SQLStorableMixin, |
| 188 | +): |
| 189 | + __tablename__ = "quota_limits" |
| 190 | + |
| 191 | + resource_name = properties.property( |
| 192 | + types.String(max_length=255), |
| 193 | + required=True, |
| 194 | + ) |
| 195 | + field_name = properties.property( |
| 196 | + types.String(max_length=255), |
| 197 | + default="", |
| 198 | + ) |
| 199 | + limit = properties.property( |
| 200 | + types.Integer(min_value=0), |
| 201 | + required=True, |
| 202 | + ) |
| 203 | + |
| 204 | + def validate(self): |
| 205 | + super().validate() |
| 206 | + resource_model = get_quota_resource_model(self.resource_name) |
| 207 | + if not self.field_name: |
| 208 | + return |
| 209 | + |
| 210 | + quota_property = resource_model.properties.properties.get(self.field_name) |
| 211 | + if quota_property is None: |
| 212 | + raise ValueError(f"Unknown quota field: {self.field_name}") |
| 213 | + if not isinstance(quota_property.get_property_type(), types.Integer): |
| 214 | + raise ValueError(f"Quota field must be an integer: {self.field_name}") |
0 commit comments