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