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 is_string_map(column):
29 return (column.type.key
31 and column.type.key.type == ovs.db.types.StringType
32 and column.type.value.type == ovs.db.types.StringType)
34 def cMembers(prefix, columnName, column, const):
36 if type.n_min == 1 and type.n_max == 1:
41 if type.is_optional_pointer():
47 key = {'name': "key_%s" % columnName,
48 'type': constify(type.key.toCType(prefix) + pointer, const),
50 value = {'name': "value_%s" % columnName,
51 'type': constify(type.value.toCType(prefix) + pointer, const),
53 members = [key, value]
55 m = {'name': columnName,
56 'type': constify(type.key.toCType(prefix) + pointer, const),
57 'comment': type.cDeclComment()}
60 if not singleton and not type.is_optional_pointer():
61 members.append({'name': 'n_%s' % columnName,
66 def printCIDLHeader(schemaFile):
67 schema = parseSchema(schemaFile)
68 prefix = schema.idlPrefix
70 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
72 #ifndef %(prefix)sIDL_HEADER
73 #define %(prefix)sIDL_HEADER 1
78 #include "ovsdb-data.h"
79 #include "ovsdb-idl-provider.h"
80 #include "uuid.h"''' % {'prefix': prefix.upper()}
82 for tableName, table in sorted(schema.tables.iteritems()):
83 structName = "%s%s" % (prefix, tableName.lower())
86 print "/* %s table. */" % tableName
87 print "struct %s {" % structName
88 print "\tstruct ovsdb_idl_row header_;"
89 for columnName, column in sorted(table.columns.iteritems()):
90 print "\n\t/* %s column. */" % columnName
91 for member in cMembers(prefix, columnName, column, False):
92 print "\t%(type)s%(name)s;%(comment)s" % member
96 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
97 for columnName in sorted(table.columns)]
98 + ["%s_N_COLUMNS" % structName.upper()])
101 for columnName in table.columns:
102 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
104 'S': structName.upper(),
106 'C': columnName.upper()}
108 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
111 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
112 const struct %(s)s *%(s)s_next(const struct %(s)s *);
113 #define %(S)s_FOR_EACH(ROW, IDL) \\
114 for ((ROW) = %(s)s_first(IDL); \\
116 (ROW) = %(s)s_next(ROW))
117 #define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
118 for ((ROW) = %(s)s_first(IDL); \\
119 (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
122 void %(s)s_delete(const struct %(s)s *);
123 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
124 ''' % {'s': structName, 'S': structName.upper()}
126 for columnName, column in sorted(table.columns.iteritems()):
127 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
130 /* Functions for fetching columns as \"struct ovsdb_datum\"s. (This is
131 rarely useful. More often, it is easier to access columns by using
132 the members of %(s)s directly.) */""" % {'s': structName}
133 for columnName, column in sorted(table.columns.iteritems()):
134 if column.type.value:
135 valueParam = ', enum ovsdb_atomic_type value_type'
138 print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
139 's': structName, 'c': columnName, 'v': valueParam}
142 for columnName, column in sorted(table.columns.iteritems()):
144 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
145 args = ['%(type)s%(name)s' % member for member
146 in cMembers(prefix, columnName, column, True)]
147 print '%s);' % ', '.join(args)
150 for columnName, column in sorted(table.columns.iteritems()):
151 if not is_string_map(column):
153 print "const char *%(s)s_get_%(c)s_value(const struct %(s)s *," \
154 " const char *key, const char *default_value);" \
155 % {'s': structName, 'c': columnName}
159 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
161 for tableName in schema.tables:
162 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
165 't': tableName.lower(),
166 'T': tableName.upper()}
167 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
169 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
170 print "\nvoid %sinit(void);" % prefix
171 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
173 def printEnum(members):
174 if len(members) == 0:
178 for member in members[:-1]:
179 print " %s," % member
180 print " %s" % members[-1]
183 def printCIDLSource(schemaFile):
184 schema = parseSchema(schemaFile)
185 prefix = schema.idlPrefix
187 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
193 #include "ovsdb-data.h"
194 #include "ovsdb-error.h"
197 /* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
198 enum { sizeof_bool = 1 };
200 enum { sizeof_bool = sizeof(bool) };
204 ''' % schema.idlHeader
207 for table in schema.tables.itervalues():
208 for column in table.columns.itervalues():
209 if is_string_map(column):
212 bsearch_strcmp(const void *a_, const void *b_)
216 return strcmp(*a, *b);
219 except StopIteration:
223 for tableName, table in sorted(schema.tables.iteritems()):
224 structName = "%s%s" % (prefix, tableName.lower())
226 static struct %(s)s *
227 %(s)s_cast(const struct ovsdb_idl_row *row)
229 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
231 ''' % {'s': structName}
234 for tableName, table in sorted(schema.tables.iteritems()):
235 structName = "%s%s" % (prefix, tableName.lower())
237 print "/* %s table. */" % (tableName)
240 for columnName, column in sorted(table.columns.iteritems()):
243 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
245 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
250 keyVar = "row->key_%s" % columnName
251 valueVar = "row->value_%s" % columnName
253 keyVar = "row->%s" % columnName
256 if (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
258 print " assert(inited);"
259 print " if (datum->n >= 1) {"
260 if not type.key.ref_table:
261 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
263 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.name.lower(), prefix, prefix.upper(), type.key.ref_table.name.upper())
266 if type.value.ref_table:
267 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
269 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.name.lower(), prefix, prefix.upper(), type.value.ref_table.name.upper())
271 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
273 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
276 if type.n_max != sys.maxint:
277 print " size_t n = MIN(%d, datum->n);" % type.n_max
283 print " assert(inited);"
284 print " %s = NULL;" % keyVar
286 print " %s = NULL;" % valueVar
287 print " row->n_%s = 0;" % columnName
288 print " for (i = 0; i < %s; i++) {" % nMax
290 if type.key.ref_table:
291 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.name.lower(), prefix, type.key.ref_table.name.lower(), prefix, prefix.upper(), type.key.ref_table.name.upper())
293 refs.append('keyRow')
295 keySrc = "datum->keys[i].%s" % type.key.type.to_string()
296 if type.value and type.value.ref_table:
297 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.name.lower(), prefix, type.value.ref_table.name.lower(), prefix, prefix.upper(), type.value.ref_table.name.upper())
298 valueSrc = "valueRow"
299 refs.append('valueRow')
301 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
303 print " if (%s) {" % ' && '.join(refs)
307 print "%sif (!row->n_%s) {" % (indent, columnName)
309 # Special case for boolean types. This is only here because
310 # sparse does not like the "normal" case ("warning: expression
311 # using sizeof bool").
312 if type.key.type == ovs.db.types.BooleanType:
313 sizeof = "sizeof_bool"
315 sizeof = "sizeof *%s" % keyVar
316 print "%s %s = xmalloc(%s * %s);" % (indent, keyVar, nMax,
319 # Special case for boolean types (see above).
320 if type.value.type == ovs.db.types.BooleanType:
321 sizeof = " * sizeof_bool"
323 sizeof = "sizeof *%s" % valueVar
324 print "%s %s = xmalloc(%s * %s);" % (indent, valueVar,
327 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
329 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
330 print "%srow->n_%s++;" % (indent, columnName)
337 for columnName, column in sorted(table.columns.iteritems()):
339 if (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
342 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
344 struct %(s)s *row = %(s)s_cast(row_);
346 assert(inited);''' % {'s': structName, 'c': columnName}
348 keyVar = "row->key_%s" % columnName
349 valueVar = "row->value_%s" % columnName
351 keyVar = "row->%s" % columnName
353 print " free(%s);" % keyVar
355 print " free(%s);" % valueVar
360 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
363 }''' % {'s': structName, 'c': columnName}
365 # First, next functions.
368 %(s)s_first(const struct ovsdb_idl *idl)
370 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
374 %(s)s_next(const struct %(s)s *row)
376 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
377 }''' % {'s': structName,
380 'T': tableName.upper()}
384 %(s)s_delete(const struct %(s)s *row)
386 ovsdb_idl_txn_delete(&row->header_);
390 %(s)s_insert(struct ovsdb_idl_txn *txn)
392 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
394 ''' % {'s': structName,
397 'T': tableName.upper()}
400 for columnName, column in sorted(table.columns.iteritems()):
403 %(s)s_verify_%(c)s(const struct %(s)s *row)
406 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
407 }''' % {'s': structName,
408 'S': structName.upper(),
410 'C': columnName.upper()}
413 for columnName, column in sorted(table.columns.iteritems()):
414 if column.type.value:
415 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
416 valueType = '\n assert(value_type == %s);' % column.type.value.toAtomicType()
417 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
423 /* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
424 * This is useful occasionally: for example, ovsdb_datum_find_key() is an
425 * easier and more efficient way to search for a given key than implementing
426 * the same operation on the "cooked" form in 'row'.
428 * 'key_type' must be %(kt)s.%(vc)s
429 * (This helps to avoid silent bugs if someone changes %(c)s's
430 * type without updating the caller.)
432 * The caller must not modify or free the returned value.
434 * Various kinds of changes can invalidate the returned value: modifying
435 * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
436 * If the returned value is needed for a long time, it is best to make a copy
437 * of it with ovsdb_datum_clone(). */
438 const struct ovsdb_datum *
439 %(s)s_get_%(c)s(const struct %(s)s *row,
440 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
442 assert(key_type == %(kt)s);%(vt)s
443 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
444 }""" % {'s': structName, 'c': columnName,
445 'kt': column.type.key.toAtomicType(),
446 'v': valueParam, 'vt': valueType, 'vc': valueComment}
449 for columnName, column in sorted(table.columns.iteritems()):
452 members = cMembers(prefix, columnName, column, True)
453 keyVar = members[0]['name']
457 valueVar = members[1]['name']
459 nVar = members[2]['name']
462 nVar = members[1]['name']
463 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
464 {'s': structName, 'c': columnName,
465 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
467 print " struct ovsdb_datum datum;"
468 if type.n_min == 1 and type.n_max == 1:
470 print " assert(inited);"
471 print " datum.n = 1;"
472 print " datum.keys = xmalloc(sizeof *datum.keys);"
473 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
475 print " datum.values = xmalloc(sizeof *datum.values);"
476 print " "+ type.value.copyCValue("datum.values[0].%s" % type.value.type.to_string(), valueVar)
478 print " datum.values = NULL;"
479 elif type.is_optional_pointer():
481 print " assert(inited);"
482 print " if (%s) {" % keyVar
483 print " datum.n = 1;"
484 print " datum.keys = xmalloc(sizeof *datum.keys);"
485 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
487 print " datum.n = 0;"
488 print " datum.keys = NULL;"
490 print " datum.values = NULL;"
494 print " assert(inited);"
495 print " datum.n = %s;" % nVar
496 print " datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
498 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
500 print " datum.values = NULL;"
501 print " for (i = 0; i < %s; i++) {" % nVar
502 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
504 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
507 valueType = type.value.toAtomicType()
509 valueType = "OVSDB_TYPE_VOID"
510 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
511 type.key.toAtomicType(), valueType)
512 print " ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
514 'S': structName.upper(),
515 'C': columnName.upper()}
518 # String Map Helpers.
519 for columnName, column in sorted(table.columns.iteritems()):
520 if not is_string_map(column):
524 const char * %(s)s_get_%(c)s_value(const struct %(s)s *row, const char *search_key, const char *default_value)
526 char **keys = row->key_%(c)s;
527 char **values = row->value_%(c)s;
528 size_t n_keys = row->n_%(c)s;
532 result_key = bsearch(&search_key, keys, n_keys, sizeof *keys,
534 return result_key ? values[result_key - keys] : default_value;
535 }""" % {'s': structName, 'c': columnName}
538 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
539 structName, structName.upper())
541 static void\n%s_columns_init(void)
543 struct ovsdb_idl_column *c;\
545 for columnName, column in sorted(table.columns.iteritems()):
546 cs = "%s_col_%s" % (structName, columnName)
547 d = {'cs': cs, 'c': columnName, 's': structName}
549 print " /* Initialize %(cs)s. */" % d
550 print " c = &%(cs)s;" % d
551 print " c->name = \"%(c)s\";" % d
552 print column.type.cInitType(" ", "c->type")
553 print " c->parse = %(s)s_parse_%(c)s;" % d
554 print " c->unparse = %(s)s_unparse_%(c)s;" % d
559 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
560 for tableName, table in sorted(schema.tables.iteritems()):
561 structName = "%s%s" % (prefix, tableName.lower())
566 print " {\"%s\", %s," % (tableName, is_root)
567 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
568 structName, structName)
569 print " sizeof(struct %s)}," % structName
573 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
574 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
575 schema.name, prefix, prefix)
578 # global init function
588 for tableName, table in sorted(schema.tables.iteritems()):
589 structName = "%s%s" % (prefix, tableName.lower())
590 print " %s_columns_init();" % structName
594 def ovsdb_escape(string):
598 raise ovs.db.error.Error("strings may not contain null bytes")
612 return '\\x%02x' % ord(c)
613 return re.sub(r'["\\\000-\037]', escape, string)
617 %(argv0)s: ovsdb schema compiler
618 usage: %(argv0)s [OPTIONS] COMMAND ARG...
620 The following commands are supported:
621 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
622 c-idl-header IDL print C header file for IDL
623 c-idl-source IDL print C source file for IDL implementation
624 nroff IDL print schema documentation in nroff format
626 The following options are also available:
627 -h, --help display this help message
628 -V, --version display version information\
629 """ % {'argv0': argv0}
632 if __name__ == "__main__":
635 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
639 except getopt.GetoptError, geo:
640 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
643 for key, value in options:
644 if key in ['-h', '--help']:
646 elif key in ['-V', '--version']:
647 print "ovsdb-idlc (Open vSwitch) @VERSION@"
648 elif key in ['-C', '--directory']:
653 optKeys = [key for key, value in options]
656 sys.stderr.write("%s: missing command argument "
657 "(use --help for help)\n" % argv0)
660 commands = {"annotate": (annotateSchema, 2),
661 "c-idl-header": (printCIDLHeader, 1),
662 "c-idl-source": (printCIDLSource, 1)}
664 if not args[0] in commands:
665 sys.stderr.write("%s: unknown command \"%s\" "
666 "(use --help for help)\n" % (argv0, args[0]))
669 func, n_args = commands[args[0]]
670 if len(args) - 1 != n_args:
671 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
673 % (argv0, args[0], n_args, len(args) - 1))
677 except ovs.db.error.Error, e:
678 sys.stderr.write("%s: %s\n" % (argv0, e))