python: Implement write support in Python IDL for OVSDB.
[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 import uuid
17
18 from ovs.db import error
19 import ovs.db.parser
20 import ovs.db.data
21 import ovs.ovsuuid
22
23 class AtomicType(object):
24     def __init__(self, name, default, python_types):
25         self.name = name
26         self.default = default
27         self.python_types = python_types
28
29     @staticmethod
30     def from_string(s):
31         if s != "void":
32             for atomic_type in ATOMIC_TYPES:
33                 if s == atomic_type.name:
34                     return atomic_type
35         raise error.Error('"%s" is not an atomic-type' % s, s)
36
37     @staticmethod
38     def from_json(json):
39         if type(json) not in [str, unicode]:
40             raise error.Error("atomic-type expected", json)
41         else:
42             return AtomicType.from_string(json)
43
44     def __str__(self):
45         return self.name
46
47     def to_string(self):
48         return self.name
49
50     def to_json(self):
51         return self.name
52
53     def default_atom(self):
54         return ovs.db.data.Atom(self, self.default)
55
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,))
62
63 ATOMIC_TYPES = [VoidType, IntegerType, RealType, BooleanType, StringType,
64                 UuidType]
65
66 def escapeCString(src):
67     dst = ""
68     for c in src:
69         if c in "\\\"":
70             dst += "\\" + c
71         elif ord(c) < 32:
72             if c == '\n':
73                 dst += '\\n'
74             elif c == '\r':
75                 dst += '\\r'
76             elif c == '\a':
77                 dst += '\\a'
78             elif c == '\b':
79                 dst += '\\b'
80             elif c == '\f':
81                 dst += '\\f'
82             elif c == '\t':
83                 dst += '\\t'
84             elif c == '\v':
85                 dst += '\\v'
86             else:
87                 dst += '\\%03o' % ord(c)
88         else:
89             dst += c
90     return dst
91
92 def commafy(x):
93     """Returns integer x formatted in decimal with thousands set off by
94     commas."""
95     return _commafy("%d" % x)
96 def _commafy(s):
97     if s.startswith('-'):
98         return '-' + _commafy(s[1:])
99     elif len(s) <= 3:
100         return s
101     else:
102         return _commafy(s[:-3]) + ',' + _commafy(s[-3:])
103
104 def returnUnchanged(x):
105     return x
106
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)
111         self.type = type_
112         self.enum = enum
113         self.min = min
114         self.max = max
115         self.min_length = min_length
116         self.max_length = max_length
117         self.ref_table_name = ref_table_name
118         if ref_table_name:
119             self.ref_type = 'strong'
120         else:
121             self.ref_type = None
122         self.ref_table = None
123
124     def default(self):
125         return ovs.db.data.Atom.default(self.type)
126
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)
135
136     def __ne__(self, other):
137         if not isinstance(other, BaseType):
138             return NotImplemented
139         else:
140             return not (self == other)
141
142     @staticmethod
143     def __parse_uint(parser, name, default):
144         value = parser.get_optional(name, [int, long])
145         if value is None:
146             value = default
147         else:
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)
152         return value
153
154     @staticmethod
155     def from_json(json):
156         if type(json) in [str, unicode]:
157             return BaseType(AtomicType.from_json(json))
158
159         parser = ovs.db.parser.Parser(json, "ovsdb type")
160         atomic_type = AtomicType.from_json(parser.get("type", [str, unicode]))
161
162         base = BaseType(atomic_type)
163
164         enum = parser.get_optional("enum", [])
165         if enum is not None:
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",
180                                                     sys.maxint)
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],
187                                                    "strong")
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)
191         parser.finish()
192
193         return base
194
195     def to_json(self):
196         if not self.has_constraints():
197             return self.type.to_json()
198
199         json = {'type': self.type.to_json()}
200
201         if self.enum:
202             json['enum'] = self.enum.to_json()
203
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
224         return json
225
226     def copy(self):
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
230         return base
231
232     def is_valid(self):
233         if self.type in (VoidType, BooleanType, UuidType):
234             return True
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
239         else:
240             return False
241
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)
246
247     def without_constraints(self):
248         return BaseType(self.type)
249
250     @staticmethod
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)
255     
256     def is_ref(self):
257         return self.type == UuidType and self.ref_table_name is not None
258
259     def is_strong_ref(self):
260         return self.is_ref() and self.ref_type == 'strong'
261
262     def is_weak_ref(self):
263         return self.is_ref() and self.ref_type == 'weak'
264
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
270             return s
271         else:
272             return self.type.to_string()
273
274     def constraintsToEnglish(self, escapeLiteral=returnUnchanged):
275         if self.enum:
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])
280             else:
281                 return 'one of %s, %s, or %s' % (literals[0],
282                                                  ', '.join(literals[1:-1]),
283                                                  literals[-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),
287                                               commafy(self.max))
288             else:
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)
293             else:
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)
298             else:
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)
303             else:
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
309         else:
310             return ''
311
312     def toCType(self, prefix):
313         if self.ref_table_name:
314             return "struct %s%s *" % (prefix, self.ref_table_name.lower())
315         else:
316             return {IntegerType: 'int64_t ',
317                     RealType: 'double ',
318                     UuidType: 'struct uuid ',
319                     BooleanType: 'bool ',
320                     StringType: 'char *'}[self.type]
321
322     def toAtomicType(self):
323         return "OVSDB_TYPE_%s" % self.type.to_string().upper()
324
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
331         else:
332             return "%(dst)s = %(src)s;" % args
333
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
339         else:
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]
345             return pattern % var
346             
347     def cInitBaseType(self, indent, var):
348         stmts = []
349         stmts.append('ovsdb_base_type_init(&%s, %s);' % (
350                 var, self.toAtomicType()))
351         if self.enum:
352             stmts.append("%s.enum_ = xmalloc(sizeof *%s.enum_);"
353                          % (var, var))
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])
375
376 class Type(object):
377     DEFAULT_MIN = 1
378     DEFAULT_MAX = 1
379
380     def __init__(self, key, value=None, n_min=DEFAULT_MIN, n_max=DEFAULT_MAX):
381         self.key = key
382         self.value = value
383         self.n_min = n_min
384         self.n_max = n_max
385
386     def copy(self):
387         if self.value is None:
388             value = None
389         else:
390             value = self.value.copy()
391         return Type(self.key.copy(), value, self.n_min, self.n_max)
392
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)
398
399     def __ne__(self, other):
400         if not isinstance(other, Type):
401             return NotImplemented
402         else:
403             return not (self == other)
404
405     def is_valid(self):
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)
410
411     def is_scalar(self):
412         return self.n_min == 1 and self.n_max == 1 and not self.value
413
414     def is_optional(self):
415         return self.n_min == 0 and self.n_max == 1
416
417     def is_composite(self):
418         return self.n_max > 1
419
420     def is_set(self):
421         return self.value is None and (self.n_min != 1 or self.n_max != 1)
422
423     def is_map(self):
424         return self.value is not None
425
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))
429
430     @staticmethod
431     def __n_from_json(json, default):
432         if json is None:
433             return default
434         elif type(json) == int and 0 <= json <= sys.maxint:
435             return json
436         else:
437             raise error.Error("bad min or max value", json)
438     
439     @staticmethod
440     def from_json(json):
441         if type(json) in [str, unicode]:
442             return Type(BaseType.from_json(json))
443
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])
449         parser.finish()
450
451         key = BaseType.from_json(key_json)
452         if value_json:
453             value = BaseType.from_json(value_json)
454         else:
455             value = None
456
457         n_min = Type.__n_from_json(min_json, Type.DEFAULT_MIN)
458
459         if max_json == 'unlimited':
460             n_max = sys.maxint
461         else:
462             n_max = Type.__n_from_json(max_json, Type.DEFAULT_MAX)
463
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)
467         return type_
468
469     def to_json(self):
470         if self.is_scalar() and not self.key.has_constraints():
471             return self.key.to_json()
472
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
482         return json
483
484     def toEnglish(self, escapeLiteral=returnUnchanged):
485         keyName = self.key.toEnglish(escapeLiteral)
486         if self.value:
487             valueName = self.value.toEnglish(escapeLiteral)
488
489         if self.is_scalar():
490             return keyName
491         elif self.is_optional():
492             if self.value:
493                 return "optional %s-%s pair" % (keyName, valueName)
494             else:
495                 return "optional %s" % keyName
496         else:
497             if self.n_max == sys.maxint:
498                 if self.n_min:
499                     quantity = "%d or more " % self.n_min
500                 else:
501                     quantity = ""
502             elif self.n_min:
503                 quantity = "%d to %d " % (self.n_min, self.n_max)
504             else:
505                 quantity = "up to %d " % self.n_max
506
507             if self.value:
508                 return "map of %s%s-%s pairs" % (quantity, keyName, valueName)
509             else:
510                 if keyName.endswith('s'):
511                     plural = keyName + "es"
512                 else:
513                     plural = keyName + "s"
514                 return "set of %s%s" % (quantity, plural)
515
516     def constraintsToEnglish(self, escapeLiteral=returnUnchanged):
517         constraints = []
518         keyConstraints = self.key.constraintsToEnglish(escapeLiteral)
519         if keyConstraints:
520             if self.value:
521                 constraints.append('key %s' % keyConstraints)
522             else:
523                 constraints.append(keyConstraints)
524
525         if self.value:
526             valueConstraints = self.value.constraintsToEnglish(escapeLiteral)
527             if valueConstraints:
528                 constraints.append('value %s' % valueConstraints)
529
530         return ', '.join(constraints)
531                 
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. */"
535         else:
536             return ""
537
538     def cInitType(self, indent, var):
539         initKey = self.key.cInitBaseType(indent, "%s.key" % var)
540         if self.value:
541             initValue = self.value.cInitBaseType(indent, "%s.value" % var)
542         else:
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:
547             n_max = "UINT_MAX"
548         else:
549             n_max = self.n_max
550         initMax = "%s%s.n_max = %s;" % (indent, var, n_max)
551         return "\n".join((initKey, initValue, initMin, initMax))
552