]> git.proxmox.com Git - mirror_ovs.git/blob - ovsdb/ovsdb-idlc.in
Merge "master" branch into "db".
[mirror_ovs.git] / ovsdb / ovsdb-idlc.in
1 #! @PYTHON@
2
3 import getopt
4 import re
5 import sys
6
7 sys.path.insert(0, "@abs_top_srcdir@/ovsdb")
8 import simplejson as json
9
10 argv0 = sys.argv[0]
11
12 class Error(Exception):
13 def __init__(self, msg):
14 Exception.__init__(self)
15 self.msg = msg
16
17 def getMember(json, name, validTypes, description, default=None):
18 if name in json:
19 member = json[name]
20 if type(member) not in validTypes:
21 raise Error("%s: type mismatch for '%s' member"
22 % (description, name))
23 return member
24 return default
25
26 def mustGetMember(json, name, expectedType, description):
27 member = getMember(json, name, expectedType, description)
28 if member == None:
29 raise Error("%s: missing '%s' member" % (description, name))
30 return member
31
32 class DbSchema:
33 def __init__(self, name, comment, tables, idlPrefix, idlHeader):
34 self.name = name
35 self.comment = comment
36 self.tables = tables
37 self.idlPrefix = idlPrefix
38 self.idlHeader = idlHeader
39
40 @staticmethod
41 def fromJson(json):
42 name = mustGetMember(json, 'name', [unicode], 'database')
43 comment = getMember(json, 'comment', [unicode], 'database')
44 tablesJson = mustGetMember(json, 'tables', [dict], 'database')
45 tables = {}
46 for name, tableJson in tablesJson.iteritems():
47 tables[name] = TableSchema.fromJson(tableJson, "%s table" % name)
48 idlPrefix = mustGetMember(json, 'idlPrefix', [unicode], 'database')
49 idlHeader = mustGetMember(json, 'idlHeader', [unicode], 'database')
50 return DbSchema(name, comment, tables, idlPrefix, idlHeader)
51
52 def toJson(self):
53 d = {"name": self.name,
54 "tables": {}}
55 for name, table in self.tables.iteritems():
56 d["tables"][name] = table.toJson()
57 if self.comment != None:
58 d["comment"] = self.comment
59 return d
60
61 class TableSchema:
62 def __init__(self, comment, columns):
63 self.comment = comment
64 self.columns = columns
65
66 @staticmethod
67 def fromJson(json, description):
68 comment = getMember(json, 'comment', [unicode], description)
69 columnsJson = mustGetMember(json, 'columns', [dict], description)
70 columns = {}
71 for name, json in columnsJson.iteritems():
72 columns[name] = ColumnSchema.fromJson(
73 json, "column %s in %s" % (name, description))
74 return TableSchema(comment, columns)
75
76 def toJson(self):
77 d = {"columns": {}}
78 for name, column in self.columns.iteritems():
79 d["columns"][name] = column.toJson()
80 if self.comment != None:
81 d["comment"] = self.comment
82 return d
83
84 class ColumnSchema:
85 def __init__(self, comment, type, persistent):
86 self.comment = comment
87 self.type = type
88 self.persistent = persistent
89
90 @staticmethod
91 def fromJson(json, description):
92 comment = getMember(json, 'comment', [unicode], description)
93 type = Type.fromJson(mustGetMember(json, 'type', [dict, unicode],
94 description),
95 'type of %s' % description)
96 ephemeral = getMember(json, 'ephemeral', [True,False], description)
97 persistent = ephemeral != True
98 return ColumnSchema(comment, type, persistent)
99
100 def toJson(self):
101 d = {"type": self.type.toJson()}
102 if self.persistent == False:
103 d["ephemeral"] = True
104 if self.comment != None:
105 d["comment"] = self.comment
106 return d
107
108 class Type:
109 def __init__(self, key, keyRefTable=None, value=None, valueRefTable=None,
110 min=1, max=1):
111 self.key = key
112 self.keyRefTable = keyRefTable
113 self.value = value
114 self.valueRefTable = valueRefTable
115 self.min = min
116 self.max = max
117
118 @staticmethod
119 def fromJson(json, description):
120 if type(json) == unicode:
121 return Type(json)
122 else:
123 key = mustGetMember(json, 'key', [unicode], description)
124 keyRefTable = getMember(json, 'keyRefTable', [unicode], description)
125 value = getMember(json, 'value', [unicode], description)
126 valueRefTable = getMember(json, 'valueRefTable', [unicode], description)
127 min = getMember(json, 'min', [int], description, 1)
128 max = getMember(json, 'max', [int, unicode], description, 1)
129 return Type(key, keyRefTable, value, valueRefTable, min, max)
130
131 def toJson(self):
132 if self.value == None and self.min == 1 and self.max == 1:
133 return self.key
134 else:
135 d = {"key": self.key}
136 if self.value != None:
137 d["value"] = self.value
138 if self.min != 1:
139 d["min"] = self.min
140 if self.max != 1:
141 d["max"] = self.max
142 return d
143
144 def parseSchema(filename):
145 file = open(filename, "r")
146 s = ""
147 for line in file:
148 if not line.startswith('//'):
149 s += line
150 return DbSchema.fromJson(json.loads(s))
151
152 def cBaseType(prefix, type, refTable=None):
153 if type == 'uuid' and refTable:
154 return "struct %s%s *" % (prefix, refTable.lower())
155 else:
156 return {'integer': 'int64_t ',
157 'real': 'double ',
158 'uuid': 'struct uuid ',
159 'boolean': 'bool ',
160 'string': 'char *'}[type]
161
162 def printCIDLHeader(schema):
163 prefix = schema.idlPrefix
164 print '''\
165 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
166
167 #ifndef %(prefix)sIDL_HEADER
168 #define %(prefix)sIDL_HEADER 1
169
170 #include <stdbool.h>
171 #include <stddef.h>
172 #include <stdint.h>
173 #include "ovsdb-idl-provider.h"
174 #include "uuid.h"''' % {'prefix': prefix.upper()}
175 for tableName, table in schema.tables.iteritems():
176 print
177 if table.comment != None:
178 print "/* %s table (%s). */" % (tableName, table.comment)
179 else:
180 print "/* %s table. */" % (tableName)
181 structName = "%s%s" % (prefix, tableName.lower())
182 print "struct %s {" % structName
183 print "\tstruct ovsdb_idl_row header_;"
184 for columnName, column in table.columns.iteritems():
185 print "\n\t/* %s column. */" % columnName
186 type = column.type
187 if type.min == 1 and type.max == 1:
188 singleton = True
189 pointer = ''
190 else:
191 singleton = False
192 pointer = '*'
193 if type.value:
194 print "\tkey_%s%s%s;" % (cBaseType(prefix, type.key, type.keyRefTable), pointer, columnName)
195 print "\tvalue_%s%s%s;" % (cBaseType(prefix, type.value, type.valueRefTable), pointer, columnName)
196 else:
197 print "\t%s%s%s;" % (cBaseType(prefix, type.key, type.keyRefTable), pointer, columnName)
198 if not singleton:
199 print "\tsize_t n_%s;" % columnName
200 print '''
201 };
202
203 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
204 const struct %(s)s *%(s)s_next(const struct %(s)s *);
205 #define %(S)s_FOR_EACH(ROW, IDL) for ((ROW) = %(s)s_first(IDL); (ROW); (ROW) = %(s)s_next(ROW))''' % {'s': structName, 'S': structName.upper()}
206 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
207 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
208
209 def printEnum(members):
210 if len(members) == 0:
211 return
212
213 print "\nenum {";
214 for member in members[:-1]:
215 print " %s," % member
216 print " %s" % members[-1]
217 print "};"
218
219 def printCIDLSource(schema):
220 prefix = schema.idlPrefix
221 print '''\
222 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
223
224 #include <config.h>
225 #include %s
226 #include <limits.h>
227 #include "ovsdb-data.h"''' % schema.idlHeader
228
229 # Table indexes.
230 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in schema.tables] + ["%sN_TABLES" % prefix.upper()])
231 print "\nstatic struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
232
233 for tableName, table in schema.tables.iteritems():
234 structName = "%s%s" % (prefix, tableName.lower())
235 print "\f"
236 if table.comment != None:
237 print "/* %s table (%s). */" % (tableName, table.comment)
238 else:
239 print "/* %s table. */" % (tableName)
240
241 # Column indexes.
242 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
243 for columnName in table.columns]
244 + ["%s_N_COLUMNS" % structName.upper()])
245
246 # Parse function.
247 print '''
248 static void
249 %s_parse(struct ovsdb_idl_row *row_)
250 {
251 struct %s *row = (struct %s *) row_;
252 const struct ovsdb_datum *datum;
253 size_t i UNUSED;
254
255 memset(row_ + 1, 0, sizeof *row - sizeof *row_);''' % (structName, structName, structName)
256
257
258 for columnName, column in table.columns.iteritems():
259 type = column.type
260 refKey = type.key == "uuid" and type.keyRefTable
261 refValue = type.value == "uuid" and type.valueRefTable
262 print
263 print " datum = &row_->fields[%s_COL_%s];" % (structName.upper(), columnName.upper())
264 if type.value:
265 keyVar = "row->key_%s" % columnName
266 valueVar = "row->value_%s" % columnName
267 else:
268 keyVar = "row->%s" % columnName
269 valueVar = None
270
271 if type.min == 1 and type.max == 1:
272 print " if (datum->n >= 1) {"
273 if not refKey:
274 print " %s = datum->keys[0].%s;" % (keyVar, type.key)
275 else:
276 print " %s = (struct %s%s *) ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid);" % (keyVar, prefix, type.keyRefTable.lower(), prefix, prefix.upper(), type.keyRefTable.upper())
277
278 if valueVar:
279 if refValue:
280 print " %s = datum->values[0].%s;" % (valueVar, type.value)
281 else:
282 print " %s = (struct %s%s *) ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid);" % (valueVar, prefix, type.valueRefTable.lower(), prefix, prefix.upper(), type.valueRefTable.upper())
283 print " }"
284 else:
285 if type.max != 'unlimited':
286 nMax = "MIN(%d, datum->n)" % type.max
287 else:
288 nMax = "datum->n"
289 print " for (i = 0; i < %s; i++) {" % nMax
290 refs = []
291 if refKey:
292 print " struct %s%s *keyRow = (struct %s%s *) ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[i].uuid);" % (prefix, type.keyRefTable.lower(), prefix, type.keyRefTable.lower(), prefix, prefix.upper(), type.keyRefTable.upper())
293 keySrc = "keyRow"
294 refs.append('keyRow')
295 else:
296 keySrc = "datum->keys[i].%s" % type.key
297 if refValue:
298 print " struct %s%s *valueRow = (struct %s%s *) ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[i].uuid);" % (prefix, type.valueRefTable.lower(), prefix, type.valueRefTable.lower(), prefix, prefix.upper(), type.valueRefTable.upper())
299 valueSrc = "valueRow"
300 refs.append('valueRow')
301 elif valueVar:
302 valueSrc = "datum->values[i].%s" % type.value
303 if refs:
304 print " if (%s) {" % ' && '.join(refs)
305 indent = " "
306 else:
307 indent = " "
308 print "%sif (!row->n_%s) {" % (indent, columnName)
309 print "%s %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
310 if valueVar:
311 print "%s %s = xmalloc(%s * sizeof %%s);" % (indent, valueVar, nMax, valueVar)
312 print "%s}" % indent
313 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
314 if valueVar:
315 print "%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
316 print "%srow->n_%s++;" % (indent, columnName)
317 if refs:
318 print " }"
319 print " }"
320 print "}"
321
322 # Unparse function.
323 nArrays = 0
324 for columnName, column in table.columns.iteritems():
325 type = column.type
326 if type.min != 1 or type.max != 1:
327 if not nArrays:
328 print '''
329 static void
330 %s_unparse(struct ovsdb_idl_row *row_)
331 {
332 struct %s *row = (struct %s *) row_;
333 ''' % (structName, structName, structName)
334 if type.value:
335 keyVar = "row->key_%s" % columnName
336 valueVar = "row->value_%s" % columnName
337 else:
338 keyVar = "row->%s" % columnName
339 valueVar = None
340 print " free(%s);" % keyVar
341 if valueVar:
342 print " free(%s);" % valueVar
343 nArrays += 1
344 if not nArrays:
345 print '''
346 static void
347 %s_unparse(struct ovsdb_idl_row *row UNUSED)
348 {''' % (structName)
349 print "}"
350
351 # First, next functions.
352 print '''
353 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *idl)
354 {
355 return (const struct %(s)s *) ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]);
356 }
357
358 const struct %(s)s *%(s)s_next(const struct %(s)s *row)
359 {
360 return (const struct %(s)s *) ovsdb_idl_next_row(&row->header_);
361 }''' % {'s': structName, 'p': prefix, 'P': prefix.upper(), 'T': tableName.upper()}
362
363 # Table columns.
364 print "\nstatic struct ovsdb_idl_column %s_columns[%s_N_COLUMNS] = {" % (
365 structName, structName.upper())
366 for columnName, column in table.columns.iteritems():
367 type = column.type
368
369 if type.value:
370 valueTypeName = type.value.upper()
371 else:
372 valueTypeName = "VOID"
373 if type.max == "unlimited":
374 max = "UINT_MAX"
375 else:
376 max = type.max
377 print " {\"%s\", {OVSDB_TYPE_%s, OVSDB_TYPE_%s, %d, %s}}," % (
378 columnName, type.key.upper(), valueTypeName,
379 type.min, max)
380 print "};"
381
382 # Table classes.
383 print "\f"
384 print "static struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
385 for tableName, table in schema.tables.iteritems():
386 structName = "%s%s" % (prefix, tableName.lower())
387 print " {\"%s\"," % tableName
388 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
389 structName, structName)
390 print " sizeof(struct %s)," % structName
391 print " %s_parse," % structName
392 print " %s_unparse}," % structName
393 print "};"
394
395 # IDL class.
396 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
397 print " %stable_classes, ARRAY_SIZE(%stable_classes)" % (prefix, prefix)
398 print "};"
399
400 def ovsdb_escape(string):
401 def escape(match):
402 c = match.group(0)
403 if c == '\0':
404 raise Error("strings may not contain null bytes")
405 elif c == '\\':
406 return '\\\\'
407 elif c == '\n':
408 return '\\n'
409 elif c == '\r':
410 return '\\r'
411 elif c == '\t':
412 return '\\t'
413 elif c == '\b':
414 return '\\b'
415 elif c == '\a':
416 return '\\a'
417 else:
418 return '\\x%02x' % ord(c)
419 return re.sub(r'["\\\000-\037]', escape, string)
420
421 def printOVSDBSchema(schema):
422 json.dump(schema.toJson(), sys.stdout, sort_keys=True, indent=2)
423
424 def usage():
425 print """\
426 %(argv0)s: ovsdb schema compiler
427 usage: %(argv0)s [OPTIONS] ACTION SCHEMA
428 where SCHEMA is the ovsdb schema to read (in JSON format).
429
430 One of the following actions must specified:
431 validate validate schema without taking any other action
432 c-idl-header print C header file for IDL
433 c-idl-source print C source file for IDL implementation
434 ovsdb-schema print ovsdb parseable schema
435
436 The following options are also available:
437 -h, --help display this help message
438 -V, --version display version information\
439 """ % {'argv0': argv0}
440 sys.exit(0)
441
442 if __name__ == "__main__":
443 try:
444 try:
445 options, args = getopt.gnu_getopt(sys.argv[1:], 'hV',
446 ['help',
447 'version'])
448 except getopt.GetoptError, geo:
449 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
450 sys.exit(1)
451
452 optKeys = [key for key, value in options]
453 if '-h' in optKeys or '--help' in optKeys:
454 usage()
455 elif '-V' in optKeys or '--version' in optKeys:
456 print "ovsdb-idlc (Open vSwitch) @VERSION@"
457 sys.exit(0)
458
459 if len(args) != 2:
460 sys.stderr.write("%s: exactly two non-option arguments are "
461 "required (use --help for help)\n" % argv0)
462 sys.exit(1)
463
464 action, inputFile = args
465 schema = parseSchema(inputFile)
466 if action == 'validate':
467 pass
468 elif action == 'ovsdb-schema':
469 printOVSDBSchema(schema)
470 elif action == 'c-idl-header':
471 printCIDLHeader(schema)
472 elif action == 'c-idl-source':
473 printCIDLSource(schema)
474 else:
475 sys.stderr.write(
476 "%s: unknown action '%s' (use --help for help)\n" %
477 (argv0, action))
478 sys.exit(1)
479 except Error, e:
480 sys.stderr.write("%s: %s\n" % (argv0, e.msg))
481 sys.exit(1)
482
483 # Local variables:
484 # mode: python
485 # End: