8 sys.path.insert(0, "@abs_top_srcdir@/ovsdb")
9 import simplejson as json
16 def __init__(self, type, values):
21 def fromJson(type_, json):
23 if len(json) == 2 and json[0] == "set":
25 for atomJson in json[1]:
26 values += [Atom.fromJson(type_.key, atomJson)]
28 values = [Atom.fromJson(type_.key, json)]
30 if len(json) != 2 or json[0] != "map":
31 raise Error("%s is not valid JSON for a map" % json)
33 for pairJson in json[1]:
34 values += [(Atom.fromJson(type_.key, pairJson[0]),
35 Atom.fromJson(type_.value, pairJson[1]))]
36 return Datum(type_, values)
38 def cInitDatum(self, var):
39 if len(self.values) == 0:
40 return ["ovsdb_datum_init_empty(%s);" % var]
42 s = ["%s->n = %d;" % (var, len(self.values))]
43 s += ["%s->keys = xmalloc(%d * sizeof *%s->keys);"
44 % (var, len(self.values), var)]
46 for i in range(len(self.values)):
50 s += key.cInitAtom("%s->keys[%d]" % (var, i))
53 s += ["%s->values = xmalloc(%d * sizeof *%s->values);"
54 % (var, len(self.values), var)]
55 for i in range(len(self.values)):
56 value = self.values[i][1]
57 s += key.cInitAtom("%s->values[%d]" % (var, i))
59 s += ["%s->values = NULL;" % var]
61 if len(self.values) > 1:
62 s += ["ovsdb_datum_sort_assert(%s, OVSDB_TYPE_%s);"
63 % (var, self.type.key.upper())]
67 def parseSchema(filename):
68 return IdlSchema.fromJson(json.load(open(filename, "r")))
70 def annotateSchema(schemaFile, annotationFile):
71 schemaJson = json.load(open(schemaFile, "r"))
72 execfile(annotationFile, globals(), {"s": schemaJson})
73 json.dump(schemaJson, sys.stdout)
75 def constify(cType, const):
77 and cType.endswith('*') and not cType.endswith('**')
78 and (cType.startswith('struct uuid') or cType.startswith('char'))):
79 return 'const %s' % cType
83 def cMembers(prefix, columnName, column, const):
85 if type.min == 1 and type.max == 1:
90 if type.isOptionalPointer():
96 key = {'name': "key_%s" % columnName,
97 'type': constify(type.key.toCType(prefix) + pointer, const),
99 value = {'name': "value_%s" % columnName,
100 'type': constify(type.value.toCType(prefix) + pointer, const),
102 members = [key, value]
104 m = {'name': columnName,
105 'type': constify(type.key.toCType(prefix) + pointer, const),
106 'comment': type.cDeclComment()}
109 if not singleton and not type.isOptionalPointer():
110 members.append({'name': 'n_%s' % columnName,
115 def printCIDLHeader(schemaFile):
116 schema = parseSchema(schemaFile)
117 prefix = schema.idlPrefix
119 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
121 #ifndef %(prefix)sIDL_HEADER
122 #define %(prefix)sIDL_HEADER 1
127 #include "ovsdb-idl-provider.h"
128 #include "uuid.h"''' % {'prefix': prefix.upper()}
130 for tableName, table in sorted(schema.tables.iteritems()):
131 structName = "%s%s" % (prefix, tableName.lower())
134 print "/* %s table. */" % tableName
135 print "struct %s {" % structName
136 print "\tstruct ovsdb_idl_row header_;"
137 for columnName, column in sorted(table.columns.iteritems()):
138 print "\n\t/* %s column. */" % columnName
139 for member in cMembers(prefix, columnName, column, False):
140 print "\t%(type)s%(name)s;%(comment)s" % member
144 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
145 for columnName in sorted(table.columns)]
146 + ["%s_N_COLUMNS" % structName.upper()])
149 for columnName in table.columns:
150 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
152 'S': structName.upper(),
154 'C': columnName.upper()}
156 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
159 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
160 const struct %(s)s *%(s)s_next(const struct %(s)s *);
161 #define %(S)s_FOR_EACH(ROW, IDL) for ((ROW) = %(s)s_first(IDL); (ROW); (ROW) = %(s)s_next(ROW))
163 void %(s)s_delete(const struct %(s)s *);
164 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
165 ''' % {'s': structName, 'S': structName.upper()}
167 for columnName, column in sorted(table.columns.iteritems()):
168 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
171 for columnName, column in sorted(table.columns.iteritems()):
173 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
174 args = ['%(type)s%(name)s' % member for member
175 in cMembers(prefix, columnName, column, True)]
176 print '%s);' % ', '.join(args)
179 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
181 for tableName in schema.tables:
182 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
185 't': tableName.lower(),
186 'T': tableName.upper()}
187 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
189 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
190 print "\nvoid %sinit(void);" % prefix
191 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
193 def printEnum(members):
194 if len(members) == 0:
198 for member in members[:-1]:
199 print " %s," % member
200 print " %s" % members[-1]
203 def printCIDLSource(schemaFile):
204 schema = parseSchema(schemaFile)
205 prefix = schema.idlPrefix
207 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
213 #include "ovsdb-data.h"
214 #include "ovsdb-error.h"
217 ''' % schema.idlHeader
220 for tableName, table in sorted(schema.tables.iteritems()):
221 structName = "%s%s" % (prefix, tableName.lower())
223 static struct %(s)s *
224 %(s)s_cast(const struct ovsdb_idl_row *row)
226 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
228 ''' % {'s': structName}
231 for tableName, table in sorted(schema.tables.iteritems()):
232 structName = "%s%s" % (prefix, tableName.lower())
234 print "/* %s table. */" % (tableName)
237 for columnName, column in sorted(table.columns.iteritems()):
240 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
242 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
247 keyVar = "row->key_%s" % columnName
248 valueVar = "row->value_%s" % columnName
250 keyVar = "row->%s" % columnName
253 if (type.min == 1 and type.max == 1) or type.isOptionalPointer():
255 print " assert(inited);"
256 print " if (datum->n >= 1) {"
257 if not type.key.refTable:
258 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type)
260 print " %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid));" % (keyVar, prefix, type.key.refTable.lower(), prefix, prefix.upper(), type.key.refTable.upper())
263 if type.value.refTable:
264 print " %s = datum->values[0].%s;" % (valueVar, type.value.type)
266 print " %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid));" % (valueVar, prefix, type.value.refTable.lower(), prefix, prefix.upper(), type.value.refTable.upper())
268 print " %s" % type.key.initCDefault(keyVar, type.min == 0)
270 print " %s" % type.value.initCDefault(valueVar, type.min == 0)
273 if type.max != 'unlimited':
274 print " size_t n = MIN(%d, datum->n);" % type.max
280 print " assert(inited);"
281 print " %s = NULL;" % keyVar
283 print " %s = NULL;" % valueVar
284 print " row->n_%s = 0;" % columnName
285 print " for (i = 0; i < %s; i++) {" % nMax
287 if type.key.refTable:
288 print " struct %s%s *keyRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[i].uuid));" % (prefix, type.key.refTable.lower(), prefix, type.key.refTable.lower(), prefix, prefix.upper(), type.key.refTable.upper())
290 refs.append('keyRow')
292 keySrc = "datum->keys[i].%s" % type.key.type
293 if type.value and type.value.refTable:
294 print " struct %s%s *valueRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[i].uuid));" % (prefix, type.value.refTable.lower(), prefix, type.value.refTable.lower(), prefix, prefix.upper(), type.value.refTable.upper())
295 valueSrc = "valueRow"
296 refs.append('valueRow')
298 valueSrc = "datum->values[i].%s" % type.value.type
300 print " if (%s) {" % ' && '.join(refs)
304 print "%sif (!row->n_%s) {" % (indent, columnName)
305 print "%s %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
307 print "%s %s = xmalloc(%s * sizeof %s);" % (indent, valueVar, nMax, valueVar)
309 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
311 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
312 print "%srow->n_%s++;" % (indent, columnName)
319 for columnName, column in sorted(table.columns.iteritems()):
321 if (type.min != 1 or type.max != 1) and not type.isOptionalPointer():
324 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
326 struct %(s)s *row = %(s)s_cast(row_);
328 assert(inited);''' % {'s': structName, 'c': columnName}
330 keyVar = "row->key_%s" % columnName
331 valueVar = "row->value_%s" % columnName
333 keyVar = "row->%s" % columnName
335 print " free(%s);" % keyVar
337 print " free(%s);" % valueVar
342 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
345 }''' % {'s': structName, 'c': columnName}
347 # First, next functions.
350 %(s)s_first(const struct ovsdb_idl *idl)
352 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
356 %(s)s_next(const struct %(s)s *row)
358 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
359 }''' % {'s': structName,
362 'T': tableName.upper()}
366 %(s)s_delete(const struct %(s)s *row)
368 ovsdb_idl_txn_delete(&row->header_);
372 %(s)s_insert(struct ovsdb_idl_txn *txn)
374 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
376 ''' % {'s': structName,
379 'T': tableName.upper()}
382 for columnName, column in sorted(table.columns.iteritems()):
385 %(s)s_verify_%(c)s(const struct %(s)s *row)
388 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
389 }''' % {'s': structName,
390 'S': structName.upper(),
392 'C': columnName.upper()}
395 for columnName, column in sorted(table.columns.iteritems()):
398 members = cMembers(prefix, columnName, column, True)
399 keyVar = members[0]['name']
403 valueVar = members[1]['name']
405 nVar = members[2]['name']
408 nVar = members[1]['name']
409 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
410 {'s': structName, 'c': columnName,
411 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
413 print " struct ovsdb_datum datum;"
414 if type.min == 1 and type.max == 1:
416 print " assert(inited);"
417 print " datum.n = 1;"
418 print " datum.keys = xmalloc(sizeof *datum.keys);"
419 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type, keyVar)
421 print " datum.values = xmalloc(sizeof *datum.values);"
422 print " "+ type.value.copyCValue("datum.values[0].%s" % type.value.type, valueVar)
424 print " datum.values = NULL;"
425 elif type.isOptionalPointer():
427 print " assert(inited);"
428 print " if (%s) {" % keyVar
429 print " datum.n = 1;"
430 print " datum.keys = xmalloc(sizeof *datum.keys);"
431 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type, keyVar)
433 print " datum.n = 0;"
434 print " datum.keys = NULL;"
436 print " datum.values = NULL;"
440 print " assert(inited);"
441 print " datum.n = %s;" % nVar
442 print " datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
444 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
446 print " datum.values = NULL;"
447 print " for (i = 0; i < %s; i++) {" % nVar
448 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type, "%s[i]" % keyVar)
450 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type, "%s[i]" % valueVar)
452 print " ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
454 'S': structName.upper(),
455 'C': columnName.upper()}
459 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
460 structName, structName.upper())
462 static void\n%s_columns_init(void)
464 struct ovsdb_idl_column *c;\
466 for columnName, column in sorted(table.columns.iteritems()):
467 cs = "%s_col_%s" % (structName, columnName)
468 d = {'cs': cs, 'c': columnName, 's': structName}
470 print " /* Initialize %(cs)s. */" % d
471 print " c = &%(cs)s;" % d
472 print " c->name = \"%(c)s\";" % d
473 print column.type.cInitType(" ", "c->type")
474 print " c->parse = %(s)s_parse_%(c)s;" % d
475 print " c->unparse = %(s)s_unparse_%(c)s;" % d
480 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
481 for tableName, table in sorted(schema.tables.iteritems()):
482 structName = "%s%s" % (prefix, tableName.lower())
483 print " {\"%s\"," % tableName
484 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
485 structName, structName)
486 print " sizeof(struct %s)}," % structName
490 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
491 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
492 schema.name, prefix, prefix)
495 # global init function
505 for tableName, table in sorted(schema.tables.iteritems()):
506 structName = "%s%s" % (prefix, tableName.lower())
507 print " %s_columns_init();" % structName
510 def ovsdb_escape(string):
514 raise Error("strings may not contain null bytes")
528 return '\\x%02x' % ord(c)
529 return re.sub(r'["\\\000-\037]', escape, string)
535 %(argv0)s: ovsdb schema compiler
536 usage: %(argv0)s [OPTIONS] COMMAND ARG...
538 The following commands are supported:
539 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
540 c-idl-header IDL print C header file for IDL
541 c-idl-source IDL print C source file for IDL implementation
542 nroff IDL print schema documentation in nroff format
544 The following options are also available:
545 -h, --help display this help message
546 -V, --version display version information\
547 """ % {'argv0': argv0}
550 if __name__ == "__main__":
553 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
557 except getopt.GetoptError, geo:
558 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
561 for key, value in options:
562 if key in ['-h', '--help']:
564 elif key in ['-V', '--version']:
565 print "ovsdb-idlc (Open vSwitch) @VERSION@"
566 elif key in ['-C', '--directory']:
571 optKeys = [key for key, value in options]
574 sys.stderr.write("%s: missing command argument "
575 "(use --help for help)\n" % argv0)
578 commands = {"annotate": (annotateSchema, 2),
579 "c-idl-header": (printCIDLHeader, 1),
580 "c-idl-source": (printCIDLSource, 1)}
582 if not args[0] in commands:
583 sys.stderr.write("%s: unknown command \"%s\" "
584 "(use --help for help)\n" % (argv0, args[0]))
587 func, n_args = commands[args[0]]
588 if len(args) - 1 != n_args:
589 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
591 % (argv0, args[0], n_args, len(args) - 1))
596 sys.stderr.write("%s: %s\n" % (argv0, e.msg))