Implement initial Python bindings for Open vSwitch database.
[sliver-openvswitch.git] / python / ovs / db / types.py
1 # Copyright (c) 2009, 2010 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)
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         try:
40             return AtomicType.from_string(json)
41         except error.Error:
42             raise error.Error("\"%s\" is not an atomic-type" % json, 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)
58 RealType = AtomicType("real", 0.0)
59 BooleanType = AtomicType("boolean", False)
60 StringType = AtomicType("string", "")
61 UuidType = AtomicType("uuid", ovs.ovsuuid.UUID.zero())
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=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 = ref_table
118
119     def default(self):
120         return ovs.db.data.Atom.default(self.type)
121
122     def __eq__(self, other):
123         if not isinstance(other, BaseType):
124             return NotImplemented
125         return (self.type == other.type and self.enum == other.enum and
126                 self.min == other.min and self.max == other.max and
127                 self.min_length == other.min_length and
128                 self.max_length == other.max_length and
129                 self.ref_table == other.ref_table)
130
131     def __ne__(self, other):
132         if not isinstance(other, BaseType):
133             return NotImplemented
134         else:
135             return not (self == other)
136
137     @staticmethod
138     def __parse_uint(parser, name, default):
139         value = parser.get_optional(name, [int, long])
140         if value is None:
141             value = default
142         else:
143             max_value = 2**32 - 1
144             if value < 0 or value > max_value:
145                 raise error.Error("%s out of valid range 0 to %d"
146                                   % (name, max_value), value)
147         return value
148
149     @staticmethod
150     def from_json(json):
151         if type(json) == unicode:
152             return BaseType(AtomicType.from_json(json))
153
154         parser = ovs.db.parser.Parser(json, "ovsdb type")
155         atomic_type = AtomicType.from_json(parser.get("type", [str, unicode]))
156
157         base = BaseType(atomic_type)
158
159         enum = parser.get_optional("enum", [])
160         if enum is not None:
161             base.enum = ovs.db.data.Datum.from_json(BaseType.get_enum_type(base.type), enum)
162         elif base.type == IntegerType:
163             base.min = parser.get_optional("minInteger", [int, long])
164             base.max = parser.get_optional("maxInteger", [int, long])
165             if base.min is not None and base.max is not None and base.min > base.max:
166                 raise error.Error("minInteger exceeds maxInteger", json)
167         elif base.type == RealType:
168             base.min = parser.get_optional("minReal", [int, long, float])
169             base.max = parser.get_optional("maxReal", [int, long, float])
170             if base.min is not None and base.max is not None and base.min > base.max:
171                 raise error.Error("minReal exceeds maxReal", json)
172         elif base.type == StringType:
173             base.min_length = BaseType.__parse_uint(parser, "minLength", 0)
174             base.max_length = BaseType.__parse_uint(parser, "maxLength",
175                                                     sys.maxint)
176             if base.min_length > base.max_length:
177                 raise error.Error("minLength exceeds maxLength", json)
178         elif base.type == UuidType:
179             base.ref_table = parser.get_optional("refTable", ['id'])
180             if base.ref_table:
181                 base.ref_type = parser.get_optional("refType", [str, unicode],
182                                                    "strong")
183                 if base.ref_type not in ['strong', 'weak']:
184                     raise error.Error("refType must be \"strong\" or \"weak\" "
185                                       "(not \"%s\")" % base.ref_type)
186         parser.finish()
187
188         return base
189
190     def to_json(self):
191         if not self.has_constraints():
192             return self.type.to_json()
193
194         json = {'type': self.type.to_json()}
195
196         if self.enum:
197             json['enum'] = self.enum.to_json()
198
199         if self.type == IntegerType:
200             if self.min is not None:
201                 json['minInteger'] = self.min
202             if self.max is not None:
203                 json['maxInteger'] = self.max
204         elif self.type == RealType:
205             if self.min is not None:
206                 json['minReal'] = self.min
207             if self.max is not None:
208                 json['maxReal'] = self.max
209         elif self.type == StringType:
210             if self.min_length != 0:
211                 json['minLength'] = self.min_length
212             if self.max_length != sys.maxint:
213                 json['maxLength'] = self.max_length
214         elif self.type == UuidType:
215             if self.ref_table:
216                 json['refTable'] = self.ref_table
217                 if self.ref_type != 'strong':
218                     json['refType'] = self.ref_type
219         return json
220
221     def clone(self):
222         return BaseType(self.type, self.enum.clone(), self.min, self.max,
223                         self.min_length, self.max_length, self.ref_table)
224
225     def is_valid(self):
226         if self.type in (VoidType, BooleanType, UuidType):
227             return True
228         elif self.type in (IntegerType, RealType):
229             return self.min is None or self.max is None or self.min <= self.max
230         elif self.type == StringType:
231             return self.min_length <= self.max_length
232         else:
233             return False
234
235     def has_constraints(self):
236         return (self.enum is not None or self.min is not None or self.max is not None or
237                 self.min_length != 0 or self.max_length != sys.maxint or
238                 self.ref_table is not None)
239
240     def without_constraints(self):
241         return BaseType(self.type)
242
243     @staticmethod
244     def get_enum_type(atomic_type):
245         """Returns the type of the 'enum' member for a BaseType whose
246         'type' is 'atomic_type'."""
247         return Type(BaseType(atomic_type), None, 1, sys.maxint)
248     
249     def is_ref(self):
250         return self.type == UuidType and self.ref_table is not None
251
252     def is_strong_ref(self):
253         return self.is_ref() and self.ref_type == 'strong'
254
255     def is_weak_ref(self):
256         return self.is_ref() and self.ref_type == 'weak'
257
258     def toEnglish(self, escapeLiteral=returnUnchanged):
259         if self.type == UuidType and self.ref_table:
260             s = escapeLiteral(self.ref_table)
261             if self.ref_type == 'weak':
262                 s = "weak reference to " + s
263             return s
264         else:
265             return self.type.to_string()
266
267     def constraintsToEnglish(self, escapeLiteral=returnUnchanged):
268         if self.enum:
269             literals = [value.toEnglish(escapeLiteral)
270                         for value in self.enum.values]
271             if len(literals) == 2:
272                 return 'either %s or %s' % (literals[0], literals[1])
273             else:
274                 return 'one of %s, %s, or %s' % (literals[0],
275                                                  ', '.join(literals[1:-1]),
276                                                  literals[-1])
277         elif self.min is not None and self.max is not None:
278             if self.type == IntegerType:
279                 return 'in range %s to %s' % (commafy(self.min),
280                                               commafy(self.max))
281             else:
282                 return 'in range %g to %g' % (self.min, self.max)
283         elif self.min is not None:
284             if self.type == IntegerType:
285                 return 'at least %s' % commafy(self.min)
286             else:
287                 return 'at least %g' % self.min
288         elif self.max is not None:
289             if self.type == IntegerType:
290                 return 'at most %s' % commafy(self.max)
291             else:
292                 return 'at most %g' % self.max
293         elif self.min_length is not None and self.max_length is not None:
294             if self.min_length == self.max_length:
295                 return 'exactly %d characters long' % (self.min_length)
296             else:
297                 return 'between %d and %d characters long' % (self.min_length, self.max_length)
298         elif self.min_length is not None:
299             return 'at least %d characters long' % self.min_length
300         elif self.max_length is not None:
301             return 'at most %d characters long' % self.max_length
302         else:
303             return ''
304
305     def toCType(self, prefix):
306         if self.ref_table:
307             return "struct %s%s *" % (prefix, self.ref_table.lower())
308         else:
309             return {IntegerType: 'int64_t ',
310                     RealType: 'double ',
311                     UuidType: 'struct uuid ',
312                     BooleanType: 'bool ',
313                     StringType: 'char *'}[self.type]
314
315     def toAtomicType(self):
316         return "OVSDB_TYPE_%s" % self.type.to_string().upper()
317
318     def copyCValue(self, dst, src):
319         args = {'dst': dst, 'src': src}
320         if self.ref_table:
321             return ("%(dst)s = %(src)s->header_.uuid;") % args
322         elif self.type == StringType:
323             return "%(dst)s = xstrdup(%(src)s);" % args
324         else:
325             return "%(dst)s = %(src)s;" % args
326
327     def initCDefault(self, var, is_optional):
328         if self.ref_table:
329             return "%s = NULL;" % var
330         elif self.type == StringType and not is_optional:
331             return "%s = \"\";" % var
332         else:
333             pattern = {IntegerType: '%s = 0;',
334                        RealType: '%s = 0.0;',
335                        UuidType: 'uuid_zero(&%s);',
336                        BooleanType: '%s = false;',
337                        StringType: '%s = NULL;'}[self.type]
338             return pattern % var
339             
340     def cInitBaseType(self, indent, var):
341         stmts = []
342         stmts.append('ovsdb_base_type_init(&%s, OVSDB_TYPE_%s);' % (
343                 var, self.type.to_string().upper()),)
344         if self.enum:
345             stmts.append("%s.enum_ = xmalloc(sizeof *%s.enum_);"
346                          % (var, var))
347             stmts += self.enum.cInitDatum("%s.enum_" % var)
348         if self.type == IntegerType:
349             if self.min is not None:
350                 stmts.append('%s.u.integer.min = INT64_C(%d);' % (var, self.min))
351             if self.max is not None:
352                 stmts.append('%s.u.integer.max = INT64_C(%d);' % (var, self.max))
353         elif self.type == RealType:
354             if self.min is not None:
355                 stmts.append('%s.u.real.min = %d;' % (var, self.min))
356             if self.max is not None:
357                 stmts.append('%s.u.real.max = %d;' % (var, self.max))
358         elif self.type == StringType:
359             if self.min_length is not None:
360                 stmts.append('%s.u.string.minLen = %d;' % (var, self.min_length))            
361             if self.max_length is not None:
362                 stmts.append('%s.u.string.maxLen = %d;' % (var, self.max_length))
363         elif self.type == UuidType:
364             if self.ref_table is not None:
365                 stmts.append('%s.u.uuid.refTableName = "%s";' % (var, escapeCString(self.ref_table)))
366         return '\n'.join([indent + stmt for stmt in stmts])
367
368 class Type(object):
369     def __init__(self, key, value=None, n_min=1, n_max=1):
370         self.key = key
371         self.value = value
372         self.n_min = n_min
373         self.n_max = n_max
374
375     def clone(self):
376         if self.value is None:
377             value = None
378         else:
379             value = self.value.clone()
380         return Type(self.key.clone(), value, self.n_min, self.n_max)
381
382     def __eq__(self, other):
383         if not isinstance(other, Type):
384             return NotImplemented
385         return (self.key == other.key and self.value == other.value and
386                 self.n_min == other.n_min and self.n_max == other.n_max)
387
388     def __ne__(self, other):
389         if not isinstance(other, BaseType):
390             return NotImplemented
391         else:
392             return not (self == other)
393
394     def is_valid(self):
395         return (self.key.type != VoidType and self.key.is_valid() and
396                 (self.value is None or
397                  (self.value.type != VoidType and self.value.is_valid())) and
398                 self.n_min <= 1 and
399                 self.n_min <= self.n_max and
400                 self.n_max >= 1)
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 json >= 0 and 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, 1)
449
450         if max_json == 'unlimited':
451             n_max = sys.maxint
452         else:
453             n_max = Type.__n_from_json(max_json, 1)            
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 != 1:
468             json["min"] = self.n_min
469         if self.n_max == sys.maxint:
470             json["max"] = "unlimited"
471         elif self.n_max != 1:
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 += ['key ' + keyConstraints]
515             else:
516                 constraints += [keyConstraints]
517
518         if self.value:
519             valueConstraints = self.value.constraintsToEnglish(escapeLiteral)
520             if valueConstraints:
521                 constraints += ['value ' + 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