1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
|
# Copyright 2016 OpenStack Foundation
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import itertools
import uuid
import netaddr
from oslo_serialization import jsonutils
from oslo_versionedobjects import fields as obj_fields
from neutron_lib._i18n import _
from neutron_lib import constants as lib_constants
from neutron_lib.db import constants as lib_db_const
from neutron_lib.objects import exceptions as o_exc
from neutron_lib.utils import net as net_utils
class HARouterEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(valid_values=lib_constants.VALID_HA_STATES)
class IPV6ModeEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(valid_values=lib_constants.IPV6_MODES)
class RangeConstrainedInteger(obj_fields.Integer):
def __init__(self, start, end, **kwargs):
try:
self._start = int(start)
self._end = int(end)
except (TypeError, ValueError) as e:
raise o_exc.NeutronRangeConstrainedIntegerInvalidLimit(
start=start, end=end) from e
super().__init__(**kwargs)
def coerce(self, obj, attr, value):
if not isinstance(value, int):
msg = _("Field value %s is not an integer") % value
raise ValueError(msg)
if not self._start <= value <= self._end:
msg = _("Field value %s is invalid") % value
raise ValueError(msg)
return super().coerce(obj, attr, value)
class IPNetworkPrefixLen(RangeConstrainedInteger):
"""IP network (CIDR) prefix length custom Enum"""
def __init__(self, **kwargs):
super().__init__(start=0, end=lib_constants.IPv6_BITS, **kwargs)
class IPNetworkPrefixLenField(obj_fields.AutoTypedField):
AUTO_TYPE = IPNetworkPrefixLen()
class PortRanges(obj_fields.FieldType):
@staticmethod
def _is_port_acceptable(port):
start = lib_constants.PORT_RANGE_MIN
end = lib_constants.PORT_RANGE_MAX
return start <= port <= end
def get_schema(self):
return {'type': ['string', 'integer']}
def _validate_port(self, attr, value):
if self._is_port_acceptable(value):
return
raise ValueError(
_('The port %(value)s does not respect the '
'range (%(min)s, %(max)s) in field %(attr)s')
% {'attr': attr,
'value': value,
'min': lib_constants.PORT_RANGE_MIN,
'max': lib_constants.PORT_RANGE_MAX})
def coerce(self, obj, attr, value):
if isinstance(value, int):
self._validate_port(attr, value)
return value
if isinstance(value, str):
if value.isnumeric():
self._validate_port(attr, int(value))
return value
values = value.split(':')
if len(values) == 2:
start, end = list(map(int, values))
if start > end:
raise ValueError(
_('The first port %(start)s must be less or equals '
'than the second port %(end)s of the port range '
'configuration %(value)s'
'in field %(attr)s.') % {
'attr': attr,
'value': value,
'start': start,
'end': end})
self._validate_port(attr, start)
self._validate_port(attr, end)
return value
raise ValueError(
_('The field %(attr)s must be in the format PORT_RANGE or'
'PORT_RANGE:PORT_RANGE (two numeric values separated '
'by a colon), and PORT_RANGE must be a numeric '
'value and respect the range '
'(%(min)s, %(max)s).') % {
'attr': attr,
'min': lib_constants.PORT_RANGE_MIN,
'max': lib_constants.PORT_RANGE_MAX})
raise ValueError(
_('An string/int PORT_RANGE or a string with '
'PORT_RANGE:PORT_RANGE format is '
'expected in field %(attr)s, not a %(type)s') % {
'attr': attr, 'type': value})
class PortRangesField(obj_fields.AutoTypedField):
AUTO_TYPE = PortRanges()
class PortRange(RangeConstrainedInteger):
def __init__(self, start=lib_constants.PORT_RANGE_MIN, **kwargs):
super().__init__(start=start,
end=lib_constants.PORT_RANGE_MAX,
**kwargs)
class PortRangeField(obj_fields.AutoTypedField):
AUTO_TYPE = PortRange()
class PortRangeWith0Field(obj_fields.AutoTypedField):
AUTO_TYPE = PortRange(start=0)
class VlanIdRange(RangeConstrainedInteger):
def __init__(self, **kwargs):
super().__init__(start=lib_constants.MIN_VLAN_TAG,
end=lib_constants.MAX_VLAN_TAG,
**kwargs)
class VlanIdRangeField(obj_fields.AutoTypedField):
AUTO_TYPE = VlanIdRange()
class ListOfIPNetworksField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.List(obj_fields.IPNetwork())
class SetOfUUIDsField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Set(obj_fields.UUID())
class DomainName(obj_fields.String):
def coerce(self, obj, attr, value):
if not isinstance(value, str):
msg = _("Field value %s is not a string") % value
raise ValueError(msg)
if len(value) > lib_db_const.FQDN_FIELD_SIZE:
msg = _("Domain name %s is too long") % value
raise ValueError(msg)
return super().coerce(obj, attr, value)
class DomainNameField(obj_fields.AutoTypedField):
AUTO_TYPE = DomainName()
class IntegerEnum(obj_fields.Integer):
def __init__(self, valid_values=None, **kwargs):
if not valid_values:
msg = _("No possible values specified")
raise ValueError(msg)
for value in valid_values:
if not isinstance(value, int):
msg = _("Possible value %s is not an integer") % value
raise ValueError(msg)
self._valid_values = valid_values
super().__init__(**kwargs)
def coerce(self, obj, attr, value):
if not isinstance(value, int):
msg = _("Field value %s is not an integer") % value
raise ValueError(msg)
if value not in self._valid_values:
msg = (
_("Field value %(value)s is not in the list "
"of valid values: %(values)s") %
{'value': value, 'values': self._valid_values}
)
raise ValueError(msg)
return super().coerce(obj, attr, value)
class IPVersionEnum(IntegerEnum):
"""IP version integer Enum"""
def __init__(self, **kwargs):
super().__init__(
valid_values=lib_constants.IP_ALLOWED_VERSIONS, **kwargs)
class IPVersionEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = IPVersionEnum()
class DscpMark(IntegerEnum):
def __init__(self, valid_values=None, **kwargs):
super().__init__(valid_values=lib_constants.VALID_DSCP_MARKS)
class DscpMarkField(obj_fields.AutoTypedField):
AUTO_TYPE = DscpMark()
class FlowDirectionEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(valid_values=lib_constants.VALID_DIRECTIONS)
class FlowDirectionAndAnyEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(
valid_values=lib_constants.VALID_DIRECTIONS_AND_ANY)
class IpamAllocationStatusEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(
valid_values=lib_constants.VALID_IPAM_ALLOCATION_STATUSES)
class EtherTypeEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(valid_values=lib_constants.VALID_ETHERTYPES)
class IpProtocolEnum(obj_fields.Enum):
"""IP protocol number Enum"""
def __init__(self, **kwargs):
super().__init__(
valid_values=list(
itertools.chain(
lib_constants.IP_PROTOCOL_MAP.keys(),
[str(v) for v in range(256)]
)
),
**kwargs)
class PortBindingStatusEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(
valid_values=lib_constants.PORT_BINDING_STATUSES)
class IpProtocolEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = IpProtocolEnum()
class MACAddress(obj_fields.FieldType):
"""MACAddress custom field.
This custom field is different from the one provided by
oslo.versionedobjects library: it uses netaddr.EUI type instead of strings.
"""
def coerce(self, obj, attr, value):
if not isinstance(value, netaddr.EUI):
msg = _("Field value %s is not a netaddr.EUI") % value
raise ValueError(msg)
return super().coerce(obj, attr, value)
@staticmethod
def to_primitive(obj, attr, value):
return str(value)
@staticmethod
def from_primitive(obj, attr, value):
try:
return net_utils.AuthenticEUI(value)
except Exception as e:
msg = _("Field value %s is not a netaddr.EUI") % value
raise ValueError(msg) from e
class MACAddressField(obj_fields.AutoTypedField):
AUTO_TYPE = MACAddress()
class DictOfMiscValues(obj_fields.FieldType):
"""DictOfMiscValues custom field
This custom field is handling dictionary with miscellaneous value types,
including integer, float, boolean and list and nested dictionaries.
"""
@staticmethod
def coerce(obj, attr, value):
if isinstance(value, dict):
return value
if isinstance(value, str):
try:
return jsonutils.loads(value)
except Exception as e:
msg = _("Field value %s is not stringified JSON") % value
raise ValueError(msg) from e
msg = (_("Field value %s is not type of dict or stringified JSON")
% value)
raise ValueError(msg)
@staticmethod
def from_primitive(obj, attr, value):
return DictOfMiscValues.coerce(obj, attr, value)
@staticmethod
def to_primitive(obj, attr, value):
return jsonutils.dumps(value)
@staticmethod
def stringify(value):
return jsonutils.dumps(value)
class DictOfMiscValuesField(obj_fields.AutoTypedField):
AUTO_TYPE = DictOfMiscValues
class ListOfDictOfMiscValuesField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.List(DictOfMiscValuesField())
class IPNetwork(obj_fields.FieldType):
"""IPNetwork custom field.
This custom field is different from the one provided by
oslo.versionedobjects library: it does not reset string representation for
the field.
"""
def coerce(self, obj, attr, value):
if not isinstance(value, netaddr.IPNetwork):
msg = _("Field value %s is not a netaddr.IPNetwork") % value
raise ValueError(msg)
return super().coerce(obj, attr, value)
@staticmethod
def to_primitive(obj, attr, value):
return str(value)
@staticmethod
def from_primitive(obj, attr, value):
try:
return net_utils.AuthenticIPNetwork(value)
except Exception as e:
msg = _("Field value %s is not a netaddr.IPNetwork") % value
raise ValueError(msg) from e
class IPNetworkField(obj_fields.AutoTypedField):
AUTO_TYPE = IPNetwork()
class UUID(obj_fields.UUID):
def coerce(self, obj, attr, value):
uuid.UUID(str(value))
return str(value)
class UUIDField(obj_fields.AutoTypedField):
AUTO_TYPE = UUID()
class FloatingIPStatusEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(
valid_values=lib_constants.VALID_FLOATINGIP_STATUS)
class RouterStatusEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(
valid_values=lib_constants.VALID_ROUTER_STATUS)
class NetworkSegmentRangeNetworkTypeEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(
valid_values=lib_constants.NETWORK_SEGMENT_RANGE_TYPES)
class NumaAffinityPoliciesEnumField(obj_fields.AutoTypedField):
AUTO_TYPE = obj_fields.Enum(valid_values=lib_constants.PORT_NUMA_POLICIES)
|