1 # Copyright (c) 2009, 2010, 2011 Nicira Networks
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
18 from ovs.db import error
23 class AtomicType(object):
24 def __init__(self, name, default, python_types):
26 self.default = default
27 self.python_types = python_types
32 for atomic_type in ATOMIC_TYPES:
33 if s == atomic_type.name:
35 raise error.Error('"%s" is not an atomic-type' % s, s)
39 if type(json) not in [str, unicode]:
40 raise error.Error("atomic-type expected", json)
42 return AtomicType.from_string(json)
53 def default_atom(self):
54 return ovs.db.data.Atom(self, self.default)
56 VoidType = AtomicType("void", None, ())
57 IntegerType = AtomicType("integer", 0, (int, long))
58 RealType = AtomicType("real", 0.0, (int, long, float))
59 BooleanType = AtomicType("boolean", False, (bool,))
60 StringType = AtomicType("string", "", (str, unicode))
61 UuidType = AtomicType("uuid", ovs.ovsuuid.zero(), (uuid.UUID,))
63 ATOMIC_TYPES = [VoidType, IntegerType, RealType, BooleanType, StringType,
66 def escapeCString(src):
87 dst += '\\%03o' % ord(c)
93 """Returns integer x formatted in decimal with thousands set off by
95 return _commafy("%d" % x)
98 return '-' + _commafy(s[1:])
102 return _commafy(s[:-3]) + ',' + _commafy(s[-3:])
104 def returnUnchanged(x):
107 class BaseType(object):
108 def __init__(self, type_, enum=None, min=None, max=None,
109 min_length = 0, max_length=sys.maxint, ref_table_name=None):
110 assert isinstance(type_, AtomicType)
115 self.min_length = min_length
116 self.max_length = max_length
117 self.ref_table_name = ref_table_name
119 self.ref_type = 'strong'
122 self.ref_table = None
125 return ovs.db.data.Atom.default(self.type)
127 def __eq__(self, other):
128 if not isinstance(other, BaseType):
129 return NotImplemented
130 return (self.type == other.type and self.enum == other.enum and
131 self.min == other.min and self.max == other.max and
132 self.min_length == other.min_length and
133 self.max_length == other.max_length and
134 self.ref_table_name == other.ref_table_name)
136 def __ne__(self, other):
137 if not isinstance(other, BaseType):
138 return NotImplemented
140 return not (self == other)
143 def __parse_uint(parser, name, default):
144 value = parser.get_optional(name, [int, long])
148 max_value = 2**32 - 1
149 if not (0 <= value <= max_value):
150 raise error.Error("%s out of valid range 0 to %d"
151 % (name, max_value), value)
156 if type(json) in [str, unicode]:
157 return BaseType(AtomicType.from_json(json))
159 parser = ovs.db.parser.Parser(json, "ovsdb type")
160 atomic_type = AtomicType.from_json(parser.get("type", [str, unicode]))
162 base = BaseType(atomic_type)
164 enum = parser.get_optional("enum", [])
166 base.enum = ovs.db.data.Datum.from_json(BaseType.get_enum_type(base.type), enum)
167 elif base.type == IntegerType:
168 base.min = parser.get_optional("minInteger", [int, long])
169 base.max = parser.get_optional("maxInteger", [int, long])
170 if base.min is not None and base.max is not None and base.min > base.max:
171 raise error.Error("minInteger exceeds maxInteger", json)
172 elif base.type == RealType:
173 base.min = parser.get_optional("minReal", [int, long, float])
174 base.max = parser.get_optional("maxReal", [int, long, float])
175 if base.min is not None and base.max is not None and base.min > base.max:
176 raise error.Error("minReal exceeds maxReal", json)
177 elif base.type == StringType:
178 base.min_length = BaseType.__parse_uint(parser, "minLength", 0)
179 base.max_length = BaseType.__parse_uint(parser, "maxLength",
181 if base.min_length > base.max_length:
182 raise error.Error("minLength exceeds maxLength", json)
183 elif base.type == UuidType:
184 base.ref_table_name = parser.get_optional("refTable", ['id'])
185 if base.ref_table_name:
186 base.ref_type = parser.get_optional("refType", [str, unicode],
188 if base.ref_type not in ['strong', 'weak']:
189 raise error.Error('refType must be "strong" or "weak" '
190 '(not "%s")' % base.ref_type)
196 if not self.has_constraints():
197 return self.type.to_json()
199 json = {'type': self.type.to_json()}
202 json['enum'] = self.enum.to_json()
204 if self.type == IntegerType:
205 if self.min is not None:
206 json['minInteger'] = self.min
207 if self.max is not None:
208 json['maxInteger'] = self.max
209 elif self.type == RealType:
210 if self.min is not None:
211 json['minReal'] = self.min
212 if self.max is not None:
213 json['maxReal'] = self.max
214 elif self.type == StringType:
215 if self.min_length != 0:
216 json['minLength'] = self.min_length
217 if self.max_length != sys.maxint:
218 json['maxLength'] = self.max_length
219 elif self.type == UuidType:
220 if self.ref_table_name:
221 json['refTable'] = self.ref_table_name
222 if self.ref_type != 'strong':
223 json['refType'] = self.ref_type
227 base = BaseType(self.type, self.enum.copy(), self.min, self.max,
228 self.min_length, self.max_length, self.ref_table_name)
229 base.ref_table = self.ref_table
233 if self.type in (VoidType, BooleanType, UuidType):
235 elif self.type in (IntegerType, RealType):
236 return self.min is None or self.max is None or self.min <= self.max
237 elif self.type == StringType:
238 return self.min_length <= self.max_length
242 def has_constraints(self):
243 return (self.enum is not None or self.min is not None or self.max is not None or
244 self.min_length != 0 or self.max_length != sys.maxint or
245 self.ref_table_name is not None)
247 def without_constraints(self):
248 return BaseType(self.type)
251 def get_enum_type(atomic_type):
252 """Returns the type of the 'enum' member for a BaseType whose
253 'type' is 'atomic_type'."""
254 return Type(BaseType(atomic_type), None, 1, sys.maxint)
257 return self.type == UuidType and self.ref_table_name is not None
259 def is_strong_ref(self):
260 return self.is_ref() and self.ref_type == 'strong'
262 def is_weak_ref(self):
263 return self.is_ref() and self.ref_type == 'weak'
265 def toEnglish(self, escapeLiteral=returnUnchanged):
266 if self.type == UuidType and self.ref_table_name:
267 s = escapeLiteral(self.ref_table_name)
268 if self.ref_type == 'weak':
269 s = "weak reference to " + s
272 return self.type.to_string()
274 def constraintsToEnglish(self, escapeLiteral=returnUnchanged):
276 literals = [value.toEnglish(escapeLiteral)
277 for value in self.enum.values]
278 if len(literals) == 2:
279 return 'either %s or %s' % (literals[0], literals[1])
281 return 'one of %s, %s, or %s' % (literals[0],
282 ', '.join(literals[1:-1]),
284 elif self.min is not None and self.max is not None:
285 if self.type == IntegerType:
286 return 'in range %s to %s' % (commafy(self.min),
289 return 'in range %g to %g' % (self.min, self.max)
290 elif self.min is not None:
291 if self.type == IntegerType:
292 return 'at least %s' % commafy(self.min)
294 return 'at least %g' % self.min
295 elif self.max is not None:
296 if self.type == IntegerType:
297 return 'at most %s' % commafy(self.max)
299 return 'at most %g' % self.max
300 elif self.min_length != 0 and self.max_length != sys.maxint:
301 if self.min_length == self.max_length:
302 return 'exactly %d characters long' % (self.min_length)
304 return 'between %d and %d characters long' % (self.min_length, self.max_length)
305 elif self.min_length != 0:
306 return 'at least %d characters long' % self.min_length
307 elif self.max_length != sys.maxint:
308 return 'at most %d characters long' % self.max_length
312 def toCType(self, prefix):
313 if self.ref_table_name:
314 return "struct %s%s *" % (prefix, self.ref_table_name.lower())
316 return {IntegerType: 'int64_t ',
318 UuidType: 'struct uuid ',
319 BooleanType: 'bool ',
320 StringType: 'char *'}[self.type]
322 def toAtomicType(self):
323 return "OVSDB_TYPE_%s" % self.type.to_string().upper()
325 def copyCValue(self, dst, src):
326 args = {'dst': dst, 'src': src}
327 if self.ref_table_name:
328 return ("%(dst)s = %(src)s->header_.uuid;") % args
329 elif self.type == StringType:
330 return "%(dst)s = xstrdup(%(src)s);" % args
332 return "%(dst)s = %(src)s;" % args
334 def initCDefault(self, var, is_optional):
335 if self.ref_table_name:
336 return "%s = NULL;" % var
337 elif self.type == StringType and not is_optional:
338 return '%s = "";' % var
340 pattern = {IntegerType: '%s = 0;',
341 RealType: '%s = 0.0;',
342 UuidType: 'uuid_zero(&%s);',
343 BooleanType: '%s = false;',
344 StringType: '%s = NULL;'}[self.type]
347 def cInitBaseType(self, indent, var):
349 stmts.append('ovsdb_base_type_init(&%s, %s);' % (
350 var, self.toAtomicType()))
352 stmts.append("%s.enum_ = xmalloc(sizeof *%s.enum_);"
354 stmts += self.enum.cInitDatum("%s.enum_" % var)
355 if self.type == IntegerType:
356 if self.min is not None:
357 stmts.append('%s.u.integer.min = INT64_C(%d);' % (var, self.min))
358 if self.max is not None:
359 stmts.append('%s.u.integer.max = INT64_C(%d);' % (var, self.max))
360 elif self.type == RealType:
361 if self.min is not None:
362 stmts.append('%s.u.real.min = %d;' % (var, self.min))
363 if self.max is not None:
364 stmts.append('%s.u.real.max = %d;' % (var, self.max))
365 elif self.type == StringType:
366 if self.min_length is not None:
367 stmts.append('%s.u.string.minLen = %d;' % (var, self.min_length))
368 if self.max_length != sys.maxint:
369 stmts.append('%s.u.string.maxLen = %d;' % (var, self.max_length))
370 elif self.type == UuidType:
371 if self.ref_table_name is not None:
372 stmts.append('%s.u.uuid.refTableName = "%s";' % (var, escapeCString(self.ref_table_name)))
373 stmts.append('%s.u.uuid.refType = OVSDB_REF_%s;' % (var, self.ref_type.upper()))
374 return '\n'.join([indent + stmt for stmt in stmts])
380 def __init__(self, key, value=None, n_min=DEFAULT_MIN, n_max=DEFAULT_MAX):
387 if self.value is None:
390 value = self.value.copy()
391 return Type(self.key.copy(), value, self.n_min, self.n_max)
393 def __eq__(self, other):
394 if not isinstance(other, Type):
395 return NotImplemented
396 return (self.key == other.key and self.value == other.value and
397 self.n_min == other.n_min and self.n_max == other.n_max)
399 def __ne__(self, other):
400 if not isinstance(other, Type):
401 return NotImplemented
403 return not (self == other)
406 return (self.key.type != VoidType and self.key.is_valid() and
407 (self.value is None or
408 (self.value.type != VoidType and self.value.is_valid())) and
409 self.n_min <= 1 <= self.n_max)
412 return self.n_min == 1 and self.n_max == 1 and not self.value
414 def is_optional(self):
415 return self.n_min == 0 and self.n_max == 1
417 def is_composite(self):
418 return self.n_max > 1
421 return self.value is None and (self.n_min != 1 or self.n_max != 1)
424 return self.value is not None
426 def is_optional_pointer(self):
427 return (self.is_optional() and not self.value
428 and (self.key.type == StringType or self.key.ref_table_name))
431 def __n_from_json(json, default):
434 elif type(json) == int and 0 <= json <= sys.maxint:
437 raise error.Error("bad min or max value", json)
441 if type(json) in [str, unicode]:
442 return Type(BaseType.from_json(json))
444 parser = ovs.db.parser.Parser(json, "ovsdb type")
445 key_json = parser.get("key", [dict, str, unicode])
446 value_json = parser.get_optional("value", [dict, str, unicode])
447 min_json = parser.get_optional("min", [int])
448 max_json = parser.get_optional("max", [int, str, unicode])
451 key = BaseType.from_json(key_json)
453 value = BaseType.from_json(value_json)
457 n_min = Type.__n_from_json(min_json, Type.DEFAULT_MIN)
459 if max_json == 'unlimited':
462 n_max = Type.__n_from_json(max_json, Type.DEFAULT_MAX)
464 type_ = Type(key, value, n_min, n_max)
465 if not type_.is_valid():
466 raise error.Error("ovsdb type fails constraint checks", json)
470 if self.is_scalar() and not self.key.has_constraints():
471 return self.key.to_json()
473 json = {"key": self.key.to_json()}
474 if self.value is not None:
475 json["value"] = self.value.to_json()
476 if self.n_min != Type.DEFAULT_MIN:
477 json["min"] = self.n_min
478 if self.n_max == sys.maxint:
479 json["max"] = "unlimited"
480 elif self.n_max != Type.DEFAULT_MAX:
481 json["max"] = self.n_max
484 def toEnglish(self, escapeLiteral=returnUnchanged):
485 keyName = self.key.toEnglish(escapeLiteral)
487 valueName = self.value.toEnglish(escapeLiteral)
491 elif self.is_optional():
493 return "optional %s-%s pair" % (keyName, valueName)
495 return "optional %s" % keyName
497 if self.n_max == sys.maxint:
499 quantity = "%d or more " % self.n_min
503 quantity = "%d to %d " % (self.n_min, self.n_max)
505 quantity = "up to %d " % self.n_max
508 return "map of %s%s-%s pairs" % (quantity, keyName, valueName)
510 if keyName.endswith('s'):
511 plural = keyName + "es"
513 plural = keyName + "s"
514 return "set of %s%s" % (quantity, plural)
516 def constraintsToEnglish(self, escapeLiteral=returnUnchanged):
518 keyConstraints = self.key.constraintsToEnglish(escapeLiteral)
521 constraints.append('key %s' % keyConstraints)
523 constraints.append(keyConstraints)
526 valueConstraints = self.value.constraintsToEnglish(escapeLiteral)
528 constraints.append('value %s' % valueConstraints)
530 return ', '.join(constraints)
532 def cDeclComment(self):
533 if self.n_min == 1 and self.n_max == 1 and self.key.type == StringType:
534 return "\t/* Always nonnull. */"
538 def cInitType(self, indent, var):
539 initKey = self.key.cInitBaseType(indent, "%s.key" % var)
541 initValue = self.value.cInitBaseType(indent, "%s.value" % var)
543 initValue = ('%sovsdb_base_type_init(&%s.value, '
544 'OVSDB_TYPE_VOID);' % (indent, var))
545 initMin = "%s%s.n_min = %s;" % (indent, var, self.n_min)
546 if self.n_max == sys.maxint:
550 initMax = "%s%s.n_max = %s;" % (indent, var, n_max)
551 return "\n".join((initKey, initValue, initMin, initMax))