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