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.key.type == ovs.db.types.BooleanType and not type.value
340 and type.n_min == 0 and type.n_max == 1):
343 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
346 }''' % {'s': structName, 'c': columnName}
347 elif (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
350 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
352 struct %(s)s *row = %(s)s_cast(row_);
354 assert(inited);''' % {'s': structName, 'c': columnName}
356 keyVar = "row->key_%s" % columnName
357 valueVar = "row->value_%s" % columnName
359 keyVar = "row->%s" % columnName
361 print " free(%s);" % keyVar
363 print " free(%s);" % valueVar
368 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
371 }''' % {'s': structName, 'c': columnName}
373 # First, next functions.
376 %(s)s_first(const struct ovsdb_idl *idl)
378 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
382 %(s)s_next(const struct %(s)s *row)
384 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
385 }''' % {'s': structName,
388 'T': tableName.upper()}
392 %(s)s_delete(const struct %(s)s *row)
394 ovsdb_idl_txn_delete(&row->header_);
398 %(s)s_insert(struct ovsdb_idl_txn *txn)
400 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
402 ''' % {'s': structName,
405 'T': tableName.upper()}
408 for columnName, column in sorted(table.columns.iteritems()):
411 %(s)s_verify_%(c)s(const struct %(s)s *row)
414 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
415 }''' % {'s': structName,
416 'S': structName.upper(),
418 'C': columnName.upper()}
421 for columnName, column in sorted(table.columns.iteritems()):
422 if column.type.value:
423 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
424 valueType = '\n assert(value_type == %s);' % column.type.value.toAtomicType()
425 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
431 /* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
432 * This is useful occasionally: for example, ovsdb_datum_find_key() is an
433 * easier and more efficient way to search for a given key than implementing
434 * the same operation on the "cooked" form in 'row'.
436 * 'key_type' must be %(kt)s.%(vc)s
437 * (This helps to avoid silent bugs if someone changes %(c)s's
438 * type without updating the caller.)
440 * The caller must not modify or free the returned value.
442 * Various kinds of changes can invalidate the returned value: modifying
443 * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
444 * If the returned value is needed for a long time, it is best to make a copy
445 * of it with ovsdb_datum_clone(). */
446 const struct ovsdb_datum *
447 %(s)s_get_%(c)s(const struct %(s)s *row,
448 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
450 assert(key_type == %(kt)s);%(vt)s
451 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
452 }""" % {'s': structName, 'c': columnName,
453 'kt': column.type.key.toAtomicType(),
454 'v': valueParam, 'vt': valueType, 'vc': valueComment}
457 for columnName, column in sorted(table.columns.iteritems()):
460 members = cMembers(prefix, columnName, column, True)
461 keyVar = members[0]['name']
465 valueVar = members[1]['name']
467 nVar = members[2]['name']
470 nVar = members[1]['name']
471 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
472 {'s': structName, 'c': columnName,
473 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
475 print " struct ovsdb_datum datum;"
476 if type.n_min == 1 and type.n_max == 1:
478 print " assert(inited);"
479 print " datum.n = 1;"
480 print " datum.keys = xmalloc(sizeof *datum.keys);"
481 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
483 print " datum.values = xmalloc(sizeof *datum.values);"
484 print " "+ type.value.copyCValue("datum.values[0].%s" % type.value.type.to_string(), valueVar)
486 print " datum.values = NULL;"
487 elif type.is_optional_pointer():
489 print " assert(inited);"
490 print " if (%s) {" % keyVar
491 print " datum.n = 1;"
492 print " datum.keys = xmalloc(sizeof *datum.keys);"
493 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
495 print " datum.n = 0;"
496 print " datum.keys = NULL;"
498 print " datum.values = NULL;"
502 print " assert(inited);"
503 print " datum.n = %s;" % nVar
504 print " datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
506 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
508 print " datum.values = NULL;"
509 print " for (i = 0; i < %s; i++) {" % nVar
510 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
512 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
515 valueType = type.value.toAtomicType()
517 valueType = "OVSDB_TYPE_VOID"
518 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
519 type.key.toAtomicType(), valueType)
520 print " ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
522 'S': structName.upper(),
523 'C': columnName.upper()}
526 # String Map Helpers.
527 for columnName, column in sorted(table.columns.iteritems()):
528 if not is_string_map(column):
532 const char * %(s)s_get_%(c)s_value(const struct %(s)s *row, const char *search_key, const char *default_value)
534 char **keys = row->key_%(c)s;
535 char **values = row->value_%(c)s;
536 size_t n_keys = row->n_%(c)s;
540 result_key = bsearch(&search_key, keys, n_keys, sizeof *keys,
542 return result_key ? values[result_key - keys] : default_value;
543 }""" % {'s': structName, 'c': columnName}
546 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
547 structName, structName.upper())
549 static void\n%s_columns_init(void)
551 struct ovsdb_idl_column *c;\
553 for columnName, column in sorted(table.columns.iteritems()):
554 cs = "%s_col_%s" % (structName, columnName)
555 d = {'cs': cs, 'c': columnName, 's': structName}
557 print " /* Initialize %(cs)s. */" % d
558 print " c = &%(cs)s;" % d
559 print " c->name = \"%(c)s\";" % d
560 print column.type.cInitType(" ", "c->type")
561 print " c->parse = %(s)s_parse_%(c)s;" % d
562 print " c->unparse = %(s)s_unparse_%(c)s;" % d
567 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
568 for tableName, table in sorted(schema.tables.iteritems()):
569 structName = "%s%s" % (prefix, tableName.lower())
574 print " {\"%s\", %s," % (tableName, is_root)
575 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
576 structName, structName)
577 print " sizeof(struct %s)}," % structName
581 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
582 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
583 schema.name, prefix, prefix)
586 # global init function
596 for tableName, table in sorted(schema.tables.iteritems()):
597 structName = "%s%s" % (prefix, tableName.lower())
598 print " %s_columns_init();" % structName
602 def ovsdb_escape(string):
606 raise ovs.db.error.Error("strings may not contain null bytes")
620 return '\\x%02x' % ord(c)
621 return re.sub(r'["\\\000-\037]', escape, string)
625 %(argv0)s: ovsdb schema compiler
626 usage: %(argv0)s [OPTIONS] COMMAND ARG...
628 The following commands are supported:
629 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
630 c-idl-header IDL print C header file for IDL
631 c-idl-source IDL print C source file for IDL implementation
632 nroff IDL print schema documentation in nroff format
634 The following options are also available:
635 -h, --help display this help message
636 -V, --version display version information\
637 """ % {'argv0': argv0}
640 if __name__ == "__main__":
643 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
647 except getopt.GetoptError, geo:
648 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
651 for key, value in options:
652 if key in ['-h', '--help']:
654 elif key in ['-V', '--version']:
655 print "ovsdb-idlc (Open vSwitch) @VERSION@"
656 elif key in ['-C', '--directory']:
661 optKeys = [key for key, value in options]
664 sys.stderr.write("%s: missing command argument "
665 "(use --help for help)\n" % argv0)
668 commands = {"annotate": (annotateSchema, 2),
669 "c-idl-header": (printCIDLHeader, 1),
670 "c-idl-source": (printCIDLSource, 1)}
672 if not args[0] in commands:
673 sys.stderr.write("%s: unknown command \"%s\" "
674 "(use --help for help)\n" % (argv0, args[0]))
677 func, n_args = commands[args[0]]
678 if len(args) - 1 != n_args:
679 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
681 % (argv0, args[0], n_args, len(args) - 1))
685 except ovs.db.error.Error, e:
686 sys.stderr.write("%s: %s\n" % (argv0, e))