| 1 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 2 |
# not use this file except in compliance with the License. You may obtain |
| 3 |
# a copy of the License at |
| 4 |
# |
| 5 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 |
# |
| 7 |
# Unless required by applicable law or agreed to in writing, software |
| 8 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 9 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 10 |
# License for the specific language governing permissions and limitations |
| 11 |
# under the License. |
| 12 |
|
| 13 |
from webob import exc |
| 14 |
|
| 15 |
from neutron_lib._i18n import _ |
| 16 |
from neutron_lib.api.definitions import network |
| 17 |
from neutron_lib.api.definitions import port |
| 18 |
from neutron_lib.api.definitions import subnet |
| 19 |
from neutron_lib.api.definitions import subnetpool |
| 20 |
from neutron_lib.api import validators |
| 21 |
from neutron_lib import constants |
| 22 |
from neutron_lib import exceptions |
| 23 |
|
| 24 |
|
| 25 |
def _validate_privileges(context, res_dict): |
| 26 |
if ('project_id' in res_dict and |
| 27 |
res_dict['project_id'] != context.project_id and |
| 28 |
not context.can_set_project_id): |
| 29 |
msg = _("Specifying 'project_id' or 'tenant_id' other than the " |
| 30 |
"authenticated project in request is not allowed for " |
| 31 |
"current user.") |
| 32 |
raise exc.HTTPBadRequest(msg) |
| 33 |
|
| 34 |
|
| 35 |
def populate_project_info(attributes): |
| 36 |
"""Ensure that both project_id and tenant_id attributes are present. |
| 37 |
|
| 38 |
If either project_id or tenant_id is present in attributes then ensure |
| 39 |
that both are present. |
| 40 |
|
| 41 |
If neither are present then attributes is not updated. |
| 42 |
|
| 43 |
:param attributes: A dictionary of resource/API attributes |
| 44 |
or API request/response dict. |
| 45 |
:returns: attributes (updated with project_id if applicable). |
| 46 |
:raises: HTTPBadRequest if the attributes project_id and tenant_id |
| 47 |
don't match. |
| 48 |
""" |
| 49 |
if 'tenant_id' in attributes and 'project_id' not in attributes: |
| 50 |
attributes['project_id'] = attributes['tenant_id'] |
| 51 |
elif 'project_id' in attributes and 'tenant_id' not in attributes: |
| 52 |
# Backward compatibility for code still using tenant_id |
| 53 |
attributes['tenant_id'] = attributes['project_id'] |
| 54 |
|
| 55 |
if attributes.get('project_id') != attributes.get('tenant_id'): |
| 56 |
msg = _("'project_id' and 'tenant_id' do not match") |
| 57 |
raise exc.HTTPBadRequest(msg) |
| 58 |
|
| 59 |
return attributes |
| 60 |
|
| 61 |
|
| 62 |
def _fill_default(res_dict, attr_name, attr_spec): |
| 63 |
# update res_dict[attr_name] record with the default value |
| 64 |
# specified in attr_spec, taking into account default_overrides_none |
| 65 |
if attr_spec.get('default_overrides_none'): |
| 66 |
if res_dict.get(attr_name) is None: |
| 67 |
res_dict[attr_name] = attr_spec.get('default') |
| 68 |
return |
| 69 |
|
| 70 |
res_dict[attr_name] = res_dict.get(attr_name, |
| 71 |
attr_spec.get('default')) |
| 72 |
|
| 73 |
|
| 74 |
def _dict_populate_defaults(attr_value, attr_spec): |
| 75 |
# attr_value: dict |
| 76 |
# attr_spec: an attribute specification dict e.g. |
| 77 |
# { |
| 78 |
# ... |
| 79 |
# 'dict_populate_defaults': True, |
| 80 |
# 'default_overrides_none': , |
| 81 |
# 'validate': { |
| 82 |
# 'type:dict': { |
| 83 |
# 'foo': { |
| 84 |
# 'default': FOO_DEFAULT, |
| 85 |
# 'type:values': [42, 43] |
| 86 |
# }, |
| 87 |
# 'bar': { |
| 88 |
# 'default': BAR_DEFAULT, |
| 89 |
# 'convert_to': converters.convert_to_boolean |
| 90 |
# } |
| 91 |
# 'baz': { |
| 92 |
# 'dict_populate_defaults': True |
| 93 |
# 'default_overrides_none': True, |
| 94 |
# 'type:dict': { |
| 95 |
# 'baz_bar: { |
| 96 |
# 'default': 77, |
| 97 |
# 'type:boolean' |
| 98 |
# }, |
| 99 |
# 'baz_foo': { |
| 100 |
# 'default': 88, |
| 101 |
# 'type:boolean' |
| 102 |
# } |
| 103 |
# } |
| 104 |
# } |
| 105 |
# } |
| 106 |
# } |
| 107 |
# } |
| 108 |
if not attr_spec.get(constants.DICT_POPULATE_DEFAULTS): |
| 109 |
return attr_value |
| 110 |
|
| 111 |
if attr_value is None or attr_value is constants.ATTR_NOT_SPECIFIED: |
| 112 |
attr_value = {} |
| 113 |
|
| 114 |
for rule_type, rule_content in attr_spec['validate'].items(): |
| 115 |
# we only recursively apply defaults for dict rules |
| 116 |
if 'dict' not in rule_type: |
| 117 |
continue |
| 118 |
for key, key_validator in rule_content.items(): |
| 119 |
validator_name, _dummy, validator_params = ( |
| 120 |
validators._extract_validator(key_validator)) |
| 121 |
|
| 122 |
# recurse if required: |
| 123 |
if 'dict' in validator_name: |
| 124 |
value = _dict_populate_defaults( |
| 125 |
attr_value.get(key), |
| 126 |
{ |
| 127 |
constants.DICT_POPULATE_DEFAULTS: key_validator.get( |
| 128 |
constants.DICT_POPULATE_DEFAULTS), |
| 129 |
'validate': {validator_name: validator_params} |
| 130 |
} |
| 131 |
) |
| 132 |
if value is not None: |
| 133 |
attr_value[key] = value |
| 134 |
|
| 135 |
_fill_default(attr_value, key, key_validator) |
| 136 |
|
| 137 |
return attr_value |
| 138 |
|
| 139 |
|
| 140 |
class AttributeInfo: |
| 141 |
"""Provides operations on a resource's attribute map. |
| 142 |
|
| 143 |
AttributeInfo wraps an API resource's attribute dict and provides methods |
| 144 |
for filling defaults, validating, converting, etc. based on the |
| 145 |
underlying attributes. |
| 146 |
""" |
| 147 |
|
| 148 |
def __init__(self, resource_attrs): |
| 149 |
"""Create a new instance that wraps the given resource attributes. |
| 150 |
|
| 151 |
:param resource_attrs: The resource's attributes that can be any |
| 152 |
of the following types: an instance of AttributeInfo, an API |
| 153 |
definition that contains a RESOURCE_ATTRIBUTE_MAP attribute or |
| 154 |
a dict of attributes for the resource. |
| 155 |
""" |
| 156 |
if isinstance(resource_attrs, AttributeInfo): |
| 157 |
resource_attrs = resource_attrs.attributes |
| 158 |
elif getattr(resource_attrs, |
| 159 |
'RESOURCE_ATTRIBUTE_MAP', None) is not None: |
| 160 |
# handle neutron_lib API definitions |
| 161 |
resource_attrs = resource_attrs.RESOURCE_ATTRIBUTE_MAP |
| 162 |
|
| 163 |
self.attributes = resource_attrs |
| 164 |
|
| 165 |
def fill_post_defaults( |
| 166 |
self, res_dict, |
| 167 |
exc_cls=lambda m: exceptions.InvalidInput(error_message=m), |
| 168 |
check_allow_post=True): |
| 169 |
"""Fill in default values for attributes in a POST request. |
| 170 |
|
| 171 |
When a POST request is made, the attributes with default values do not |
| 172 |
need to be specified by the user. This function fills in the values of |
| 173 |
any unspecified attributes if they have a default value. |
| 174 |
|
| 175 |
If an attribute is not specified and it does not have a default value, |
| 176 |
an exception is raised. |
| 177 |
|
| 178 |
If an attribute is specified and it is not allowed in POST requests, an |
| 179 |
exception is raised. The caller can override this behavior by setting |
| 180 |
check_allow_post=False (used by some internal admin operations). |
| 181 |
|
| 182 |
:param res_dict: The resource attributes from the request. |
| 183 |
:param exc_cls: Exception to be raised on error that must take |
| 184 |
a single error message as it's only constructor arg. |
| 185 |
:param check_allow_post: Raises an exception if a non-POST-able |
| 186 |
attribute is specified. |
| 187 |
:raises: exc_cls If check_allow_post is True and this instance of |
| 188 |
ResourceAttributes doesn't support POST. |
| 189 |
""" |
| 190 |
for attr, attr_vals in self.attributes.items(): |
| 191 |
if attr_vals['allow_post']: |
| 192 |
value = _dict_populate_defaults( |
| 193 |
res_dict.get(attr, constants.ATTR_NOT_SPECIFIED), |
| 194 |
attr_vals) |
| 195 |
if value is not constants.ATTR_NOT_SPECIFIED: |
| 196 |
res_dict[attr] = value |
| 197 |
|
| 198 |
if 'default' not in attr_vals and attr not in res_dict: |
| 199 |
msg = _("Failed to parse request. Required " |
| 200 |
"attribute '%s' not specified") % attr |
| 201 |
raise exc_cls(msg) |
| 202 |
|
| 203 |
_fill_default(res_dict, attr, attr_vals) |
| 204 |
elif check_allow_post: |
| 205 |
if attr in res_dict: |
| 206 |
msg = _("Attribute '%s' not allowed in POST") % attr |
| 207 |
raise exc_cls(msg) |
| 208 |
|
| 209 |
def convert_values( |
| 210 |
self, res_dict, |
| 211 |
exc_cls=lambda m: exceptions.InvalidInput(error_message=m)): |
| 212 |
"""Convert and validate attribute values for a request. |
| 213 |
|
| 214 |
:param res_dict: The resource attributes from the request. |
| 215 |
:param exc_cls: Exception to be raised on error that must take |
| 216 |
a single error message as it's only constructor arg. |
| 217 |
:raises: exc_cls If any errors occur converting/validating the |
| 218 |
res_dict. |
| 219 |
""" |
| 220 |
for attr, attr_vals in self.attributes.items(): |
| 221 |
if (attr not in res_dict or |
| 222 |
res_dict[attr] is constants.ATTR_NOT_SPECIFIED): |
| 223 |
continue |
| 224 |
# Convert values if necessary |
| 225 |
if 'convert_to' in attr_vals: |
| 226 |
res_dict[attr] = attr_vals['convert_to'](res_dict[attr]) |
| 227 |
# Check that configured values are correct |
| 228 |
if 'validate' not in attr_vals: |
| 229 |
continue |
| 230 |
for rule in attr_vals['validate']: |
| 231 |
validator = validators.get_validator(rule) |
| 232 |
res = validator(res_dict[attr], |
| 233 |
attr_vals['validate'][rule]) |
| 234 |
if res: |
| 235 |
msg_dict = {'attr': attr, 'reason': res} |
| 236 |
msg = _("Invalid input for %(attr)s. " |
| 237 |
"Reason: %(reason)s.") % msg_dict |
| 238 |
raise exc_cls(msg) |
| 239 |
|
| 240 |
def _project_id_required(self, res_dict): |
| 241 |
return (('tenant_id' in self.attributes or |
| 242 |
'project_id' in self.attributes) and |
| 243 |
'project_id' not in res_dict) |
| 244 |
|
| 245 |
def populate_project_id(self, context, res_dict, is_create): |
| 246 |
"""Populate the owner information in a request body. |
| 247 |
|
| 248 |
Ensure both project_id and tenant_id attributes are present. |
| 249 |
Validate that the requestor has the required privileges. |
| 250 |
For a create request, copy owner info from context to request body |
| 251 |
if needed and verify that owner is specified if required. |
| 252 |
|
| 253 |
:param context: The request context. |
| 254 |
:param res_dict: The resource attributes from the request. |
| 255 |
:param attr_info: The attribute map for the resource. |
| 256 |
:param is_create: Is this a create request? |
| 257 |
:raises: HTTPBadRequest If neither the project_id nor tenant_id |
| 258 |
are specified in the res_dict. |
| 259 |
|
| 260 |
""" |
| 261 |
populate_project_info(res_dict) |
| 262 |
_validate_privileges(context, res_dict) |
| 263 |
|
| 264 |
if is_create and self._project_id_required(res_dict): |
| 265 |
if context.project_id: |
| 266 |
res_dict['project_id'] = context.project_id |
| 267 |
|
| 268 |
# For backward compatibility |
| 269 |
res_dict['tenant_id'] = context.project_id |
| 270 |
|
| 271 |
else: |
| 272 |
msg = _("Running without keystone AuthN requires " |
| 273 |
"that tenant_id is specified") |
| 274 |
raise exc.HTTPBadRequest(msg) |
| 275 |
|
| 276 |
def verify_attributes(self, attrs_to_verify): |
| 277 |
"""Reject unknown attributes. |
| 278 |
|
| 279 |
Consumers should ensure the project info is populated in the |
| 280 |
attrs_to_verify before calling this method. |
| 281 |
|
| 282 |
:param attrs_to_verify: The attributes to verify against this |
| 283 |
resource attributes. |
| 284 |
:raises: HTTPBadRequest: If attrs_to_verify contains any unrecognized |
| 285 |
for this resource attributes instance. |
| 286 |
""" |
| 287 |
extra_keys = set(attrs_to_verify.keys()) - set(self.attributes.keys()) |
| 288 |
if extra_keys: |
| 289 |
msg = _("Unrecognized attribute(s) '%s'") % ', '.join(extra_keys) |
| 290 |
raise exc.HTTPBadRequest(msg) |
| 291 |
|
| 292 |
|
| 293 |
def _core_resource_attributes(): |
| 294 |
resources = {} |
| 295 |
for core_def in [network.RESOURCE_ATTRIBUTE_MAP, |
| 296 |
port.RESOURCE_ATTRIBUTE_MAP, |
| 297 |
subnet.RESOURCE_ATTRIBUTE_MAP, |
| 298 |
subnetpool.RESOURCE_ATTRIBUTE_MAP]: |
| 299 |
resources.update(core_def) |
| 300 |
return resources |
| 301 |
|
| 302 |
|
| 303 |
# populate core resources into singleton global |
| 304 |
RESOURCES = _core_resource_attributes() |
| 305 |
|
| 306 |
|
| 307 |
def retrieve_valid_sort_keys(attr_info): |
| 308 |
"""Retrieve sort keys from `attr_info` dict. |
| 309 |
|
| 310 |
Iterate the `attr_info`, filter and return the attributes that are |
| 311 |
defined with `is_sort_key=True`. |
| 312 |
|
| 313 |
:param attr_info: The attribute dict for common neutron resource. |
| 314 |
:returns: Set of sort keys. |
| 315 |
""" |
| 316 |
return {attr for attr, schema in attr_info.items() |
| 317 |
if schema.get('is_sort_key', False)} |