14 def parseSchema(filename):
15 return ovs.db.schema.IdlSchema.from_json(ovs.json.from_file(filename))
17 def annotateSchema(schemaFile, annotationFile):
18 schemaJson = ovs.json.from_file(schemaFile)
19 execfile(annotationFile, globals(), {"s": schemaJson})
20 ovs.json.to_stream(schemaJson, sys.stdout)
22 def constify(cType, const):
23 if (const and cType.endswith('*') and not cType.endswith('**')):
24 return 'const %s' % cType
28 def cMembers(prefix, columnName, column, const):
30 if type.n_min == 1 and type.n_max == 1:
35 if type.is_optional_pointer():
41 key = {'name': "key_%s" % columnName,
42 'type': constify(type.key.toCType(prefix) + pointer, const),
44 value = {'name': "value_%s" % columnName,
45 'type': constify(type.value.toCType(prefix) + pointer, const),
47 members = [key, value]
49 m = {'name': columnName,
50 'type': constify(type.key.toCType(prefix) + pointer, const),
51 'comment': type.cDeclComment()}
54 if not singleton and not type.is_optional_pointer():
55 members.append({'name': 'n_%s' % columnName,
60 def printCIDLHeader(schemaFile):
61 schema = parseSchema(schemaFile)
62 prefix = schema.idlPrefix
64 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
66 #ifndef %(prefix)sIDL_HEADER
67 #define %(prefix)sIDL_HEADER 1
72 #include "ovsdb-data.h"
73 #include "ovsdb-idl-provider.h"
74 #include "uuid.h"''' % {'prefix': prefix.upper()}
76 for tableName, table in sorted(schema.tables.iteritems()):
77 structName = "%s%s" % (prefix, tableName.lower())
80 print "/* %s table. */" % tableName
81 print "struct %s {" % structName
82 print "\tstruct ovsdb_idl_row header_;"
83 for columnName, column in sorted(table.columns.iteritems()):
84 print "\n\t/* %s column. */" % columnName
85 for member in cMembers(prefix, columnName, column, False):
86 print "\t%(type)s%(name)s;%(comment)s" % member
90 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
91 for columnName in sorted(table.columns)]
92 + ["%s_N_COLUMNS" % structName.upper()])
95 for columnName in table.columns:
96 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
98 'S': structName.upper(),
100 'C': columnName.upper()}
102 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
105 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
106 const struct %(s)s *%(s)s_next(const struct %(s)s *);
107 #define %(S)s_FOR_EACH(ROW, IDL) \\
108 for ((ROW) = %(s)s_first(IDL); \\
110 (ROW) = %(s)s_next(ROW))
111 #define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
112 for ((ROW) = %(s)s_first(IDL); \\
113 (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
116 void %(s)s_delete(const struct %(s)s *);
117 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
118 ''' % {'s': structName, 'S': structName.upper()}
120 for columnName, column in sorted(table.columns.iteritems()):
121 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
124 /* Functions for fetching columns as \"struct ovsdb_datum\"s. (This is
125 rarely useful. More often, it is easier to access columns by using
126 the members of %(s)s directly.) */""" % {'s': structName}
127 for columnName, column in sorted(table.columns.iteritems()):
128 if column.type.value:
129 valueParam = ', enum ovsdb_atomic_type value_type'
132 print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
133 's': structName, 'c': columnName, 'v': valueParam}
136 for columnName, column in sorted(table.columns.iteritems()):
138 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
139 args = ['%(type)s%(name)s' % member for member
140 in cMembers(prefix, columnName, column, True)]
141 print '%s);' % ', '.join(args)
144 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
146 for tableName in schema.tables:
147 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
150 't': tableName.lower(),
151 'T': tableName.upper()}
152 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
154 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
155 print "\nvoid %sinit(void);" % prefix
156 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
158 def printEnum(members):
159 if len(members) == 0:
163 for member in members[:-1]:
164 print " %s," % member
165 print " %s" % members[-1]
168 def printCIDLSource(schemaFile):
169 schema = parseSchema(schemaFile)
170 prefix = schema.idlPrefix
172 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
178 #include "ovsdb-data.h"
179 #include "ovsdb-error.h"
182 ''' % schema.idlHeader
185 for tableName, table in sorted(schema.tables.iteritems()):
186 structName = "%s%s" % (prefix, tableName.lower())
188 static struct %(s)s *
189 %(s)s_cast(const struct ovsdb_idl_row *row)
191 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
193 ''' % {'s': structName}
196 for tableName, table in sorted(schema.tables.iteritems()):
197 structName = "%s%s" % (prefix, tableName.lower())
199 print "/* %s table. */" % (tableName)
202 for columnName, column in sorted(table.columns.iteritems()):
205 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
207 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
212 keyVar = "row->key_%s" % columnName
213 valueVar = "row->value_%s" % columnName
215 keyVar = "row->%s" % columnName
218 if (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
220 print " assert(inited);"
221 print " if (datum->n >= 1) {"
222 if not type.key.ref_table:
223 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
225 print " %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid));" % (keyVar, prefix, type.key.ref_table.lower(), prefix, prefix.upper(), type.key.ref_table.upper())
228 if type.value.ref_table:
229 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
231 print " %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid));" % (valueVar, prefix, type.value.ref_table.lower(), prefix, prefix.upper(), type.value.ref_table.upper())
233 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
235 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
238 if type.n_max != sys.maxint:
239 print " size_t n = MIN(%d, datum->n);" % type.n_max
245 print " assert(inited);"
246 print " %s = NULL;" % keyVar
248 print " %s = NULL;" % valueVar
249 print " row->n_%s = 0;" % columnName
250 print " for (i = 0; i < %s; i++) {" % nMax
252 if type.key.ref_table:
253 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.ref_table.lower(), prefix, type.key.ref_table.lower(), prefix, prefix.upper(), type.key.ref_table.upper())
255 refs.append('keyRow')
257 keySrc = "datum->keys[i].%s" % type.key.type.to_string()
258 if type.value and type.value.ref_table:
259 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.ref_table.lower(), prefix, type.value.ref_table.lower(), prefix, prefix.upper(), type.value.ref_table.upper())
260 valueSrc = "valueRow"
261 refs.append('valueRow')
263 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
265 print " if (%s) {" % ' && '.join(refs)
269 print "%sif (!row->n_%s) {" % (indent, columnName)
270 print "%s %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
272 print "%s %s = xmalloc(%s * sizeof *%s);" % (indent, valueVar, nMax, valueVar)
274 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
276 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
277 print "%srow->n_%s++;" % (indent, columnName)
284 for columnName, column in sorted(table.columns.iteritems()):
286 if (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
289 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
291 struct %(s)s *row = %(s)s_cast(row_);
293 assert(inited);''' % {'s': structName, 'c': columnName}
295 keyVar = "row->key_%s" % columnName
296 valueVar = "row->value_%s" % columnName
298 keyVar = "row->%s" % columnName
300 print " free(%s);" % keyVar
302 print " free(%s);" % valueVar
307 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
310 }''' % {'s': structName, 'c': columnName}
312 # First, next functions.
315 %(s)s_first(const struct ovsdb_idl *idl)
317 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
321 %(s)s_next(const struct %(s)s *row)
323 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
324 }''' % {'s': structName,
327 'T': tableName.upper()}
331 %(s)s_delete(const struct %(s)s *row)
333 ovsdb_idl_txn_delete(&row->header_);
337 %(s)s_insert(struct ovsdb_idl_txn *txn)
339 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
341 ''' % {'s': structName,
344 'T': tableName.upper()}
347 for columnName, column in sorted(table.columns.iteritems()):
350 %(s)s_verify_%(c)s(const struct %(s)s *row)
353 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
354 }''' % {'s': structName,
355 'S': structName.upper(),
357 'C': columnName.upper()}
360 for columnName, column in sorted(table.columns.iteritems()):
361 if column.type.value:
362 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
363 valueType = '\n assert(value_type == %s);' % column.type.value.toAtomicType()
364 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
370 /* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
371 * This is useful occasionally: for example, ovsdb_datum_find_key() is an
372 * easier and more efficient way to search for a given key than implementing
373 * the same operation on the "cooked" form in 'row'.
375 * 'key_type' must be %(kt)s.%(vc)s
376 * (This helps to avoid silent bugs if someone changes %(c)s's
377 * type without updating the caller.)
379 * The caller must not modify or free the returned value.
381 * Various kinds of changes can invalidate the returned value: modifying
382 * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
383 * If the returned value is needed for a long time, it is best to make a copy
384 * of it with ovsdb_datum_clone(). */
385 const struct ovsdb_datum *
386 %(s)s_get_%(c)s(const struct %(s)s *row,
387 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
389 assert(key_type == %(kt)s);%(vt)s
390 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
391 }""" % {'s': structName, 'c': columnName,
392 'kt': column.type.key.toAtomicType(),
393 'v': valueParam, 'vt': valueType, 'vc': valueComment}
396 for columnName, column in sorted(table.columns.iteritems()):
399 members = cMembers(prefix, columnName, column, True)
400 keyVar = members[0]['name']
404 valueVar = members[1]['name']
406 nVar = members[2]['name']
409 nVar = members[1]['name']
410 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
411 {'s': structName, 'c': columnName,
412 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
414 print " struct ovsdb_datum datum;"
415 if type.n_min == 1 and type.n_max == 1:
417 print " assert(inited);"
418 print " datum.n = 1;"
419 print " datum.keys = xmalloc(sizeof *datum.keys);"
420 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
422 print " datum.values = xmalloc(sizeof *datum.values);"
423 print " "+ type.value.copyCValue("datum.values[0].%s" % type.value.type.to_string(), valueVar)
425 print " datum.values = NULL;"
426 elif type.is_optional_pointer():
428 print " assert(inited);"
429 print " if (%s) {" % keyVar
430 print " datum.n = 1;"
431 print " datum.keys = xmalloc(sizeof *datum.keys);"
432 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
434 print " datum.n = 0;"
435 print " datum.keys = NULL;"
437 print " datum.values = NULL;"
441 print " assert(inited);"
442 print " datum.n = %s;" % nVar
443 print " datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
445 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
447 print " datum.values = NULL;"
448 print " for (i = 0; i < %s; i++) {" % nVar
449 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
451 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
454 valueType = type.value.toAtomicType()
456 valueType = "OVSDB_TYPE_VOID"
457 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
458 type.key.toAtomicType(), valueType)
459 print " ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
461 'S': structName.upper(),
462 'C': columnName.upper()}
466 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
467 structName, structName.upper())
469 static void\n%s_columns_init(void)
471 struct ovsdb_idl_column *c;\
473 for columnName, column in sorted(table.columns.iteritems()):
474 cs = "%s_col_%s" % (structName, columnName)
475 d = {'cs': cs, 'c': columnName, 's': structName}
477 print " /* Initialize %(cs)s. */" % d
478 print " c = &%(cs)s;" % d
479 print " c->name = \"%(c)s\";" % d
480 print column.type.cInitType(" ", "c->type")
481 print " c->parse = %(s)s_parse_%(c)s;" % d
482 print " c->unparse = %(s)s_unparse_%(c)s;" % d
487 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
488 for tableName, table in sorted(schema.tables.iteritems()):
489 structName = "%s%s" % (prefix, tableName.lower())
494 print " {\"%s\", %s," % (tableName, is_root)
495 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
496 structName, structName)
497 print " sizeof(struct %s)}," % structName
501 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
502 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
503 schema.name, prefix, prefix)
506 # global init function
516 for tableName, table in sorted(schema.tables.iteritems()):
517 structName = "%s%s" % (prefix, tableName.lower())
518 print " %s_columns_init();" % structName
521 def ovsdb_escape(string):
525 raise ovs.db.error.Error("strings may not contain null bytes")
539 return '\\x%02x' % ord(c)
540 return re.sub(r'["\\\000-\037]', escape, string)
546 %(argv0)s: ovsdb schema compiler
547 usage: %(argv0)s [OPTIONS] COMMAND ARG...
549 The following commands are supported:
550 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
551 c-idl-header IDL print C header file for IDL
552 c-idl-source IDL print C source file for IDL implementation
553 nroff IDL print schema documentation in nroff format
555 The following options are also available:
556 -h, --help display this help message
557 -V, --version display version information\
558 """ % {'argv0': argv0}
561 if __name__ == "__main__":
564 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
568 except getopt.GetoptError, geo:
569 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
572 for key, value in options:
573 if key in ['-h', '--help']:
575 elif key in ['-V', '--version']:
576 print "ovsdb-idlc (Open vSwitch) @VERSION@"
577 elif key in ['-C', '--directory']:
582 optKeys = [key for key, value in options]
585 sys.stderr.write("%s: missing command argument "
586 "(use --help for help)\n" % argv0)
589 commands = {"annotate": (annotateSchema, 2),
590 "c-idl-header": (printCIDLHeader, 1),
591 "c-idl-source": (printCIDLSource, 1)}
593 if not args[0] in commands:
594 sys.stderr.write("%s: unknown command \"%s\" "
595 "(use --help for help)\n" % (argv0, args[0]))
598 func, n_args = commands[args[0]]
599 if len(args) - 1 != n_args:
600 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
602 % (argv0, args[0], n_args, len(args) - 1))
606 except ovs.db.error.Error, e:
607 sys.stderr.write("%s: %s\n" % (argv0, e))