| 1 |
# |
| 2 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
# you may not use this file except in compliance with the License. |
| 4 |
# You may obtain a copy of the License at |
| 5 |
# |
| 6 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
# |
| 8 |
# Unless required by applicable law or agreed to in writing, software |
| 9 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| 11 |
# implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
from oslo_utils import timeutils |
| 16 |
import sqlalchemy as sa |
| 17 |
from sqlalchemy import event # noqa |
| 18 |
from sqlalchemy.ext.associationproxy import association_proxy |
| 19 |
from sqlalchemy.orm import attributes |
| 20 |
from sqlalchemy.orm import declared_attr |
| 21 |
from sqlalchemy.orm import session as se |
| 22 |
|
| 23 |
from neutron_lib._i18n import _ |
| 24 |
from neutron_lib.db import constants as db_const |
| 25 |
from neutron_lib.db import model_base |
| 26 |
from neutron_lib.db import sqlalchemytypes |
| 27 |
|
| 28 |
|
| 29 |
class StandardAttribute(model_base.BASEV2): |
| 30 |
"""Common table to associate all Neutron API resources. |
| 31 |
|
| 32 |
By having Neutron objects related to this table, we can associate new |
| 33 |
tables that apply to many Neutron objects (e.g. timestamps, rbac entries) |
| 34 |
to this table to avoid schema duplication while maintaining referential |
| 35 |
integrity. |
| 36 |
|
| 37 |
NOTE(kevinbenton): This table should not have more columns added to it |
| 38 |
unless we are absolutely certain the new column will have a value for |
| 39 |
every single type of Neutron resource. Otherwise this table will be filled |
| 40 |
with NULL entries for combinations that don't make sense. Additionally, |
| 41 |
by keeping this table small we can ensure that performance isn't adversely |
| 42 |
impacted for queries on objects. |
| 43 |
""" |
| 44 |
|
| 45 |
# sqlite doesn't support auto increment on big integers so we use big int |
| 46 |
# for everything but sqlite |
| 47 |
id = sa.Column(sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), |
| 48 |
primary_key=True, autoincrement=True) |
| 49 |
|
| 50 |
# NOTE(kevinbenton): this column is redundant information, but it allows |
| 51 |
# operators/devs to look at the contents of this table and know which table |
| 52 |
# the corresponding object is in. |
| 53 |
# 255 was selected as a max just because it's the varchar ceiling in mysql |
| 54 |
# before a 2-byte prefix is required. We shouldn't get anywhere near this |
| 55 |
# limit with our table names... |
| 56 |
resource_type = sa.Column(sa.String(255), nullable=False) |
| 57 |
description = sa.Column(sa.String(db_const.DESCRIPTION_FIELD_SIZE)) |
| 58 |
|
| 59 |
revision_number = sa.Column( |
| 60 |
sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), |
| 61 |
server_default='0', nullable=False) |
| 62 |
created_at = sa.Column(sqlalchemytypes.TruncatedDateTime, |
| 63 |
default=timeutils.utcnow) |
| 64 |
updated_at = sa.Column(sqlalchemytypes.TruncatedDateTime, |
| 65 |
onupdate=timeutils.utcnow) |
| 66 |
|
| 67 |
__mapper_args__ = { |
| 68 |
# see http://docs.sqlalchemy.org/en/latest/orm/versioning.html for |
| 69 |
# details about how this works |
| 70 |
"version_id_col": revision_number, |
| 71 |
"confirm_deleted_rows": False, |
| 72 |
"version_id_generator": False # revision plugin increments manually |
| 73 |
} |
| 74 |
|
| 75 |
def bump_revision(self): |
| 76 |
if self.revision_number is None: |
| 77 |
# this is a brand new object uncommitted so we don't bump now |
| 78 |
return |
| 79 |
self.revision_number += 1 |
| 80 |
|
| 81 |
def _set_updated_revision_number(self, revision_number, updated_at): |
| 82 |
attributes.set_committed_value( |
| 83 |
self, "revision_number", revision_number) |
| 84 |
attributes.set_committed_value( |
| 85 |
self, "updated_at", updated_at) |
| 86 |
|
| 87 |
@property |
| 88 |
def _effective_standard_attribute_id(self): |
| 89 |
return self.id |
| 90 |
|
| 91 |
|
| 92 |
class HasStandardAttributes: |
| 93 |
|
| 94 |
@classmethod |
| 95 |
def get_api_collections(cls): |
| 96 |
"""Define the API collection this object will appear under. |
| 97 |
|
| 98 |
This should return a list of API collections that the object |
| 99 |
will be exposed under. Most should be exposed in just one |
| 100 |
collection (e.g. the network model is just exposed under |
| 101 |
'networks'). |
| 102 |
|
| 103 |
This is used by the standard attr extensions to discover which |
| 104 |
resources need to be extended with the standard attr fields |
| 105 |
(e.g. created_at/updated_at/etc). |
| 106 |
""" |
| 107 |
# NOTE(kevinbenton): can't use abc because the metaclass conflicts |
| 108 |
# with the declarative base others inherit from. |
| 109 |
if hasattr(cls, 'api_collections'): |
| 110 |
return cls.api_collections |
| 111 |
raise NotImplementedError(_("%s must define api_collections") % cls) |
| 112 |
|
| 113 |
@classmethod |
| 114 |
def get_api_sub_resources(cls): |
| 115 |
"""Define the API sub-resources this object will appear under. |
| 116 |
|
| 117 |
This should return a list of API sub-resources that the object |
| 118 |
will be exposed under. |
| 119 |
|
| 120 |
This is used by the standard attr extensions to discover which |
| 121 |
sub-resources need to be extended with the standard attr fields |
| 122 |
(e.g. created_at/updated_at/etc). |
| 123 |
""" |
| 124 |
try: |
| 125 |
return cls.api_sub_resources |
| 126 |
except AttributeError: |
| 127 |
return [] |
| 128 |
|
| 129 |
@classmethod |
| 130 |
def get_collection_resource_map(cls): |
| 131 |
try: |
| 132 |
return cls.collection_resource_map |
| 133 |
except AttributeError as e: |
| 134 |
raise NotImplementedError( |
| 135 |
_("%s must define collection_resource_map") % cls) from e |
| 136 |
|
| 137 |
@classmethod |
| 138 |
def validate_tag_support(cls): |
| 139 |
return getattr(cls, 'tag_support', False) |
| 140 |
|
| 141 |
@declared_attr |
| 142 |
def standard_attr_id(cls): |
| 143 |
return sa.Column( |
| 144 |
sa.BigInteger().with_variant(sa.Integer(), 'sqlite'), |
| 145 |
sa.ForeignKey(StandardAttribute.id, ondelete="CASCADE"), |
| 146 |
unique=True, |
| 147 |
nullable=False |
| 148 |
) |
| 149 |
|
| 150 |
# NOTE(kevinbenton): we have to disable the following pylint check because |
| 151 |
# it thinks we are overriding this method in the __init__ method. |
| 152 |
# pylint: disable=method-hidden |
| 153 |
@declared_attr |
| 154 |
def standard_attr(cls): |
| 155 |
return sa.orm.relationship(StandardAttribute, |
| 156 |
lazy='joined', |
| 157 |
cascade='all, delete-orphan', |
| 158 |
single_parent=True, |
| 159 |
uselist=False) |
| 160 |
|
| 161 |
@property |
| 162 |
def _effective_standard_attribute_id(self): |
| 163 |
return self.standard_attr_id |
| 164 |
|
| 165 |
def __init__(self, *args, **kwargs): |
| 166 |
standard_attr_keys = ['description', 'created_at', |
| 167 |
'updated_at', 'revision_number'] |
| 168 |
standard_attr_kwargs = {} |
| 169 |
for key in standard_attr_keys: |
| 170 |
if key in kwargs: |
| 171 |
standard_attr_kwargs[key] = kwargs.pop(key) |
| 172 |
super().__init__(*args, **kwargs) |
| 173 |
# here we automatically create the related standard attribute object |
| 174 |
self.standard_attr = StandardAttribute( |
| 175 |
resource_type=self.__tablename__, **standard_attr_kwargs) |
| 176 |
|
| 177 |
@declared_attr |
| 178 |
def description(cls): |
| 179 |
return association_proxy('standard_attr', 'description') |
| 180 |
|
| 181 |
@declared_attr |
| 182 |
def created_at(cls): |
| 183 |
return association_proxy('standard_attr', 'created_at') |
| 184 |
|
| 185 |
@declared_attr |
| 186 |
def updated_at(cls): |
| 187 |
return association_proxy('standard_attr', 'updated_at') |
| 188 |
|
| 189 |
def update(self, new_dict): |
| 190 |
# ignore the timestamps if they were passed in. For example, this |
| 191 |
# happens if code calls update_port with modified results of get_port |
| 192 |
new_dict.pop('created_at', None) |
| 193 |
new_dict.pop('updated_at', None) |
| 194 |
super().update(new_dict) |
| 195 |
|
| 196 |
@declared_attr |
| 197 |
def revision_number(cls): |
| 198 |
return association_proxy('standard_attr', 'revision_number') |
| 199 |
|
| 200 |
def bump_revision(self): |
| 201 |
# SQLAlchemy will bump the version for us automatically if the |
| 202 |
# standard attr record is being modified, but we must call this |
| 203 |
# for all other modifications or when relevant children are being |
| 204 |
# modified (e.g. fixed_ips change should bump port revision) |
| 205 |
self.standard_attr.bump_revision() |
| 206 |
|
| 207 |
def _set_updated_revision_number(self, revision_number, updated_at): |
| 208 |
self.standard_attr._set_updated_revision_number( |
| 209 |
revision_number, updated_at) |
| 210 |
|
| 211 |
|
| 212 |
def _resource_model_map_helper(rs_map, resource, subclass): |
| 213 |
if resource in rs_map: |
| 214 |
raise RuntimeError(_("Model %(sub)s tried to register for API " |
| 215 |
"resource %(res)s which conflicts with model " |
| 216 |
"%(other)s.") % |
| 217 |
{'sub': subclass, |
| 218 |
'other': rs_map[resource], |
| 219 |
'res': resource}) |
| 220 |
rs_map[resource] = subclass |
| 221 |
|
| 222 |
|
| 223 |
def get_standard_attr_resource_model_map(include_resources=True, |
| 224 |
include_sub_resources=True): |
| 225 |
rs_map = {} |
| 226 |
for subclass in HasStandardAttributes.__subclasses__(): |
| 227 |
if include_resources: |
| 228 |
for resource in subclass.get_api_collections(): |
| 229 |
_resource_model_map_helper(rs_map, resource, subclass) |
| 230 |
if include_sub_resources: |
| 231 |
for sub_resource in subclass.get_api_sub_resources(): |
| 232 |
_resource_model_map_helper(rs_map, sub_resource, subclass) |
| 233 |
return rs_map |
| 234 |
|
| 235 |
|
| 236 |
def get_tag_resource_parent_map(): |
| 237 |
parent_map = {} |
| 238 |
for subclass in HasStandardAttributes.__subclasses__(): |
| 239 |
if subclass.validate_tag_support(): |
| 240 |
for collection, resource in (subclass.get_collection_resource_map() |
| 241 |
.items()): |
| 242 |
if collection in parent_map: |
| 243 |
msg = (_("API parent %(collection)s/%(resource)s for " |
| 244 |
"model %(subclass)s is already registered.") % |
| 245 |
{'collection': collection, 'resource': resource, |
| 246 |
'subclass': subclass}) |
| 247 |
raise RuntimeError(msg) |
| 248 |
parent_map[collection] = resource |
| 249 |
return parent_map |
| 250 |
|
| 251 |
|
| 252 |
@event.listens_for(se.Session, 'after_bulk_delete') |
| 253 |
def throw_exception_on_bulk_delete_of_listened_for_objects(delete_context): |
| 254 |
if hasattr(delete_context.mapper.class_, 'revises_on_change'): |
| 255 |
raise RuntimeError(_("%s may not be deleted in bulk because it " |
| 256 |
"bumps the revision of other resources via " |
| 257 |
"SQLAlchemy event handlers, which are not " |
| 258 |
"compatible with bulk deletes.") % |
| 259 |
delete_context.mapper.class_) |