ovs.ovsuuid: Get rid of ovs.ovsuuid.UUID class.
[sliver-openvswitch.git] / python / ovs / db / types.py
1 # Copyright (c) 2009, 2010, 2011 Nicira Networks
2 #
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:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import sys
16
17 from ovs.db import error
18 import ovs.db.parser
19 import ovs.db.data
20 import ovs.ovsuuid
21
22 class AtomicType(object):
23     def __init__(self, name, default):
24         self.name = name
25         self.default = default
26
27     @staticmethod
28     def from_string(s):
29         if s != "void":
30             for atomic_type in ATOMIC_TYPES:
31                 if s == atomic_type.name:
32                     return atomic_type
33         raise error.Error('"%s" is not an atomic-type' % s, s)
34
35     @staticmethod
36     def from_json(json):
37         if type(json) not in [str, unicode]:
38             raise error.Error("atomic-type expected", json)
39         else:
40             return AtomicType.from_string(json)
41
42     def __str__(self):
43         return self.name
44
45     def to_string(self):
46         return self.name
47
48     def to_json(self):
49         return self.name
50
51     def default_atom(self):
52         return ovs.db.data.Atom(self, self.default)
53
54 VoidType = AtomicType("void", None)
55 IntegerType = AtomicType("integer", 0)
56 RealType = AtomicType("real", 0.0)
57 BooleanType = AtomicType("boolean", False)
58 StringType = AtomicType("string", "")
59 UuidType = AtomicType("uuid", ovs.ovsuuid.zero())
60
61 ATOMIC_TYPES = [VoidType, IntegerType, RealType, BooleanType, StringType,
62                 UuidType]
63
64 def escapeCString(src):
65     dst = ""
66     for c in src:
67         if c in "\\\"":
68             dst += "\\" + c
69         elif ord(c) < 32:
70             if c == '\n':
71                 dst += '\\n'
72             elif c == '\r':
73                 dst += '\\r'
74             elif c == '\a':
75                 dst += '\\a'
76             elif c == '\b':
77                 dst += '\\b'
78             elif c == '\f':
79                 dst += '\\f'
80             elif c == '\t':
81                 dst += '\\t'
82             elif c == '\v':
83                 dst += '\\v'
84             else:
85                 dst += '\\%03o' % ord(c)
86         else:
87             dst += c
88     return dst
89
90 def commafy(x):
91     """Returns integer x formatted in decimal with thousands set off by
92     commas."""
93     return _commafy("%d" % x)
94 def _commafy(s):
95     if s.startswith('-'):
96         return '-' + _commafy(s[1:])
97     elif len(s) <= 3:
98         return s
99     else:
100         return _commafy(s[:-3]) + ',' + _commafy(s[-3:])
101
102 def returnUnchanged(x):
103     return x
104
105 class BaseType(object):
106     def __init__(self, type_, enum=None, min=None, max=None,
107                  min_length = 0, max_length=sys.maxint, ref_table=None):
108         assert isinstance(type_, AtomicType)
109         self.type = type_
110         self.enum = enum
111         self.min = min
112         self.max = max
113         self.min_length = min_length
114         self.max_length = max_length
115         self.ref_table = ref_table
116         if ref_table:
117             self.ref_type = 'strong'
118         else:
119             self.ref_type = None
120
121     def default(self):
122         return ovs.db.data.Atom.default(self.type)
123
124     def __eq__(self, other):
125         if not isinstance(other, BaseType):
126             return NotImplemented
127         return (self.type == other.type and self.enum == other.enum and
128                 self.min == other.min and self.max == other.max and
129                 self.min_length == other.min_length and
130                 self.max_length == other.max_length and
131                 self.ref_table == other.ref_table)
132
133     def __ne__(self, other):
134         if not isinstance(other, BaseType):
135             return NotImplemented
136         else:
137             return not (self == other)
138
139     @staticmethod
140     def __parse_uint(parser, name, default):
141         value = parser.get_optional(name, [int, long])
142         if value is None:
143             value = default
144         else:
145             max_value = 2**32 - 1
146             if not (0 <= value <= max_value):
147                 raise error.Error("%s out of valid range 0 to %d"
148                                   % (name, max_value), value)
149         return value
150
151     @staticmethod
152     def from_json(json):
153         if type(json) == unicode:
154             return BaseType(AtomicType.from_json(json))
155
156         parser = ovs.db.parser.Parser(json, "ovsdb type")
157         atomic_type = AtomicType.from_json(parser.get("type", [str, unicode]))
158
159         base = BaseType(atomic_type)
160
161         enum = parser.get_optional("enum", [])
162         if enum is not None:
163             base.enum = ovs.db.data.Datum.from_json(BaseType.get_enum_type(base.type), enum)
164         elif base.type == IntegerType:
165             base.min = parser.get_optional("minInteger", [int, long])
166             base.max = parser.get_optional("maxInteger", [int, long])
167             if base.min is not None and base.max is not None and base.min > base.max:
168                 raise error.Error("minInteger exceeds maxInteger", json)
169         elif base.type == RealType:
170             base.min = parser.get_optional("minReal", [int, long, float])
171             base.max = parser.get_optional("maxReal", [int, long, float])
172             if base.min is not None and base.max is not None and base.min > base.max:
173                 raise error.Error("minReal exceeds maxReal", json)
174         elif base.type == StringType:
175             base.min_length = BaseType.__parse_uint(parser, "minLength", 0)
176             base.max_length = BaseType.__parse_uint(parser, "maxLength",
177                                                     sys.maxint)
178             if base.min_length > base.max_length:
179                 raise error.Error("minLength exceeds maxLength", json)
180         elif base.type == UuidType:
181             base.ref_table = parser.get_optional("refTable", ['id'])
182             if base.ref_table:
183                 base.ref_type = parser.get_optional("refType", [str, unicode],
184                                                    "strong")
185                 if base.ref_type not in ['strong', 'weak']:
186                     raise error.Error('refType must be "strong" or "weak" '
187                                       '(not "%s")' % base.ref_type)
188         parser.finish()
189
190         return base
191
192     def to_json(self):
193         if not self.has_constraints():
194             return self.type.to_json()
195
196         json = {'type': self.type.to_json()}
197
198         if self.enum:
199             json['enum'] = self.enum.to_json()
200
201         if self.type == IntegerType:
202             if self.min is not None:
203                 json['minInteger'] = self.min
204             if self.max is not None:
205                 json['maxInteger'] = self.max
206         elif self.type == RealType:
207             if self.min is not None:
208                 json['minReal'] = self.min
209             if self.max is not None:
210                 json['maxReal'] = self.max
211         elif self.type == StringType:
212             if self.min_length != 0:
213                 json['minLength'] = self.min_length
214             if self.max_length != sys.maxint:
215                 json['maxLength'] = self.max_length
216         elif self.type == UuidType:
217             if self.ref_table:
218                 json['refTable'] = self.ref_table
219                 if self.ref_type != 'strong':
220                     json['refType'] = self.ref_type
221         return json
222
223     def clone(self):
224         return BaseType(self.type, self.enum.clone(), self.min, self.max,
225                         self.min_length, self.max_length, self.ref_table)
226
227     def is_valid(self):
228         if self.type in (VoidType, BooleanType, UuidType):
229             return True
230         elif self.type in (IntegerType, RealType):
231             return self.min is None or self.max is None or self.min <= self.max
232         elif self.type == StringType:
233             return self.min_length <= self.max_length
234         else:
235             return False
236
237     def has_constraints(self):
238         return (self.enum is not None or self.min is not None or self.max is not None or
239                 self.min_length != 0 or self.max_length != sys.maxint or
240                 self.ref_table is not None)
241
242     def without_constraints(self):
243         return BaseType(self.type)
244
245     @staticmethod
246     def get_enum_type(atomic_type):
247         """Returns the type of the 'enum' member for a BaseType whose
248         'type' is 'atomic_type'."""
249         return Type(BaseType(atomic_type), None, 1, sys.maxint)
250     
251     def is_ref(self):
252         return self.type == UuidType and self.ref_table is not None
253
254     def is_strong_ref(self):
255         return self.is_ref() and self.ref_type == 'strong'
256
257     def is_weak_ref(self):
258         return self.is_ref() and self.ref_type == 'weak'
259
260     def toEnglish(self, escapeLiteral=returnUnchanged):
261         if self.type == UuidType and self.ref_table:
262             s = escapeLiteral(self.ref_table)
263             if self.ref_type == 'weak':
264                 s = "weak reference to " + s
265             return s
266         else:
267             return self.type.to_string()
268
269     def constraintsToEnglish(self, escapeLiteral=returnUnchanged):
270         if self.enum:
271             literals = [value.toEnglish(escapeLiteral)
272                         for value in self.enum.values]
273             if len(literals) == 2:
274                 return 'either %s or %s' % (literals[0], literals[1])
275             else:
276                 return 'one of %s, %s, or %s' % (literals[0],
277                                                  ', '.join(literals[1:-1]),
278                                                  literals[-1])
279         elif self.min is not None and self.max is not None:
280             if self.type == IntegerType:
281                 return 'in range %s to %s' % (commafy(self.min),
282                                               commafy(self.max))
283             else:
284                 return 'in range %g to %g' % (self.min, self.max)
285         elif self.min is not None:
286             if self.type == IntegerType:
287                 return 'at least %s' % commafy(self.min)
288             else:
289                 return 'at least %g' % self.min
290         elif self.max is not None:
291             if self.type == IntegerType:
292                 return 'at most %s' % commafy(self.max)
293             else:
294                 return 'at most %g' % self.max
295         elif self.min_length != 0 and self.max_length != sys.maxint:
296             if self.min_length == self.max_length:
297                 return 'exactly %d characters long' % (self.min_length)
298             else:
299                 return 'between %d and %d characters long' % (self.min_length, self.max_length)
300         elif self.min_length != 0:
301             return 'at least %d characters long' % self.min_length
302         elif self.max_length != sys.maxint:
303             return 'at most %d characters long' % self.max_length
304         else:
305             return ''
306
307     def toCType(self, prefix):
308         if self.ref_table:
309             return "struct %s%s *" % (prefix, self.ref_table.lower())
310         else:
311             return {IntegerType: 'int64_t ',
312                     RealType: 'double ',
313                     UuidType: 'struct uuid ',
314                     BooleanType: 'bool ',
315                     StringType: 'char *'}[self.type]
316
317     def toAtomicType(self):
318         return "OVSDB_TYPE_%s" % self.type.to_string().upper()
319
320     def copyCValue(self, dst, src):
321         args = {'dst': dst, 'src': src}
322         if self.ref_table:
323             return ("%(dst)s = %(src)s->header_.uuid;") % args
324         elif self.type == StringType:
325             return "%(dst)s = xstrdup(%(src)s);" % args
326         else:
327             return "%(dst)s = %(src)s;" % args
328
329     def initCDefault(self, var, is_optional):
330         if self.ref_table:
331             return "%s = NULL;" % var
332         elif self.type == StringType and not is_optional:
333             return '%s = "";' % var
334         else:
335             pattern = {IntegerType: '%s = 0;',
336                        RealType: '%s = 0.0;',
337                        UuidType: 'uuid_zero(&%s);',
338                        BooleanType: '%s = false;',
339                        StringType: '%s = NULL;'}[self.type]
340             return pattern % var
341             
342     def cInitBaseType(self, indent, var):
343         stmts = []
344         stmts.append('ovsdb_base_type_init(&%s, %s);' % (
345                 var, self.toAtomicType()))
346         if self.enum:
347             stmts.append("%s.enum_ = xmalloc(sizeof *%s.enum_);"
348                          % (var, var))
349             stmts += self.enum.cInitDatum("%s.enum_" % var)
350         if self.type == IntegerType:
351             if self.min is not None:
352                 stmts.append('%s.u.integer.min = INT64_C(%d);' % (var, self.min))
353             if self.max is not None:
354                 stmts.append('%s.u.integer.max = INT64_C(%d);' % (var, self.max))
355         elif self.type == RealType:
356             if self.min is not None:
357                 stmts.append('%s.u.real.min = %d;' % (var, self.min))
358             if self.max is not None:
359                 stmts.append('%s.u.real.max = %d;' % (var, self.max))
360         elif self.type == StringType:
361             if self.min_length is not None:
362                 stmts.append('%s.u.string.minLen = %d;' % (var, self.min_length))            
363             if self.max_length != sys.maxint:
364                 stmts.append('%s.u.string.maxLen = %d;' % (var, self.max_length))
365         elif self.type == UuidType:
366             if self.ref_table is not None:
367                 stmts.append('%s.u.uuid.refTableName = "%s";' % (var, escapeCString(self.ref_table)))
368                 stmts.append('%s.u.uuid.refType = OVSDB_REF_%s;' % (var, self.ref_type.upper()))
369         return '\n'.join([indent + stmt for stmt in stmts])
370
371 class Type(object):
372     DEFAULT_MIN = 1
373     DEFAULT_MAX = 1
374
375     def __init__(self, key, value=None, n_min=DEFAULT_MIN, n_max=DEFAULT_MAX):
376         self.key = key
377         self.value = value
378         self.n_min = n_min
379         self.n_max = n_max
380
381     def clone(self):
382         if self.value is None:
383             value = None
384         else:
385             value = self.value.clone()
386         return Type(self.key.clone(), value, self.n_min, self.n_max)
387
388     def __eq__(self, other):
389         if not isinstance(other, Type):
390             return NotImplemented
391         return (self.key == other.key and self.value == other.value and
392                 self.n_min == other.n_min and self.n_max == other.n_max)
393
394     def __ne__(self, other):
395         if not isinstance(other, Type):
396             return NotImplemented
397         else:
398             return not (self == other)
399
400     def is_valid(self):
401         return (self.key.type != VoidType and self.key.is_valid() and
402                 (self.value is None or
403                  (self.value.type != VoidType and self.value.is_valid())) and
404                 self.n_min <= 1 <= self.n_max)
405
406     def is_scalar(self):
407         return self.n_min == 1 and self.n_max == 1 and not self.value
408
409     def is_optional(self):
410         return self.n_min == 0 and self.n_max == 1
411
412     def is_composite(self):
413         return self.n_max > 1
414
415     def is_set(self):
416         return self.value is None and (self.n_min != 1 or self.n_max != 1)
417
418     def is_map(self):
419         return self.value is not None
420
421     def is_optional_pointer(self):
422         return (self.is_optional() and not self.value
423                 and (self.key.type == StringType or self.key.ref_table))
424
425     @staticmethod
426     def __n_from_json(json, default):
427         if json is None:
428             return default
429         elif type(json) == int and 0 <= json <= sys.maxint:
430             return json
431         else:
432             raise error.Error("bad min or max value", json)
433     
434     @staticmethod
435     def from_json(json):
436         if type(json) in [str, unicode]:
437             return Type(BaseType.from_json(json))
438
439         parser = ovs.db.parser.Parser(json, "ovsdb type")
440         key_json = parser.get("key", [dict, unicode])
441         value_json = parser.get_optional("value", [dict, unicode])
442         min_json = parser.get_optional("min", [int])
443         max_json = parser.get_optional("max", [int, str, unicode])
444         parser.finish()
445
446         key = BaseType.from_json(key_json)
447         if value_json:
448             value = BaseType.from_json(value_json)
449         else:
450             value = None
451
452         n_min = Type.__n_from_json(min_json, Type.DEFAULT_MIN)
453
454         if max_json == 'unlimited':
455             n_max = sys.maxint
456         else:
457             n_max = Type.__n_from_json(max_json, Type.DEFAULT_MAX)
458
459         type_ = Type(key, value, n_min, n_max)
460         if not type_.is_valid():
461             raise error.Error("ovsdb type fails constraint checks", json)
462         return type_
463
464     def to_json(self):
465         if self.is_scalar() and not self.key.has_constraints():
466             return self.key.to_json()
467
468         json = {"key": self.key.to_json()}
469         if self.value is not None:
470             json["value"] = self.value.to_json()
471         if self.n_min != Type.DEFAULT_MIN:
472             json["min"] = self.n_min
473         if self.n_max == sys.maxint:
474             json["max"] = "unlimited"
475         elif self.n_max != Type.DEFAULT_MAX:
476             json["max"] = self.n_max
477         return json
478
479     def toEnglish(self, escapeLiteral=returnUnchanged):
480         keyName = self.key.toEnglish(escapeLiteral)
481         if self.value:
482             valueName = self.value.toEnglish(escapeLiteral)
483
484         if self.is_scalar():
485             return keyName
486         elif self.is_optional():
487             if self.value:
488                 return "optional %s-%s pair" % (keyName, valueName)
489             else:
490                 return "optional %s" % keyName
491         else:
492             if self.n_max == sys.maxint:
493                 if self.n_min:
494                     quantity = "%d or more " % self.n_min
495                 else:
496                     quantity = ""
497             elif self.n_min:
498                 quantity = "%d to %d " % (self.n_min, self.n_max)
499             else:
500                 quantity = "up to %d " % self.n_max
501
502             if self.value:
503                 return "map of %s%s-%s pairs" % (quantity, keyName, valueName)
504             else:
505                 if keyName.endswith('s'):
506                     plural = keyName + "es"
507                 else:
508                     plural = keyName + "s"
509                 return "set of %s%s" % (quantity, plural)
510
511     def constraintsToEnglish(self, escapeLiteral=returnUnchanged):
512         constraints = []
513         keyConstraints = self.key.constraintsToEnglish(escapeLiteral)
514         if keyConstraints:
515             if self.value:
516                 constraints.append('key %s' % keyConstraints)
517             else:
518                 constraints.append(keyConstraints)
519
520         if self.value:
521             valueConstraints = self.value.constraintsToEnglish(escapeLiteral)
522             if valueConstraints:
523                 constraints.append('value %s' % valueConstraints)
524
525         return ', '.join(constraints)
526                 
527     def cDeclComment(self):
528         if self.n_min == 1 and self.n_max == 1 and self.key.type == StringType:
529             return "\t/* Always nonnull. */"
530         else:
531             return ""
532
533     def cInitType(self, indent, var):
534         initKey = self.key.cInitBaseType(indent, "%s.key" % var)
535         if self.value:
536             initValue = self.value.cInitBaseType(indent, "%s.value" % var)
537         else:
538             initValue = ('%sovsdb_base_type_init(&%s.value, '
539                          'OVSDB_TYPE_VOID);' % (indent, var))
540         initMin = "%s%s.n_min = %s;" % (indent, var, self.n_min)
541         if self.n_max == sys.maxint:
542             n_max = "UINT_MAX"
543         else:
544             n_max = self.n_max
545         initMax = "%s%s.n_max = %s;" % (indent, var, n_max)
546         return "\n".join((initKey, initValue, initMin, initMax))
547