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):
32 return [{'name': columnName,
33 'type': 'struct smap ',
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"
81 #include "uuid.h"''' % {'prefix': prefix.upper()}
83 for tableName, table in sorted(schema.tables.iteritems()):
84 structName = "%s%s" % (prefix, tableName.lower())
87 print "/* %s table. */" % tableName
88 print "struct %s {" % structName
89 print "\tstruct ovsdb_idl_row header_;"
90 for columnName, column in sorted(table.columns.iteritems()):
91 print "\n\t/* %s column. */" % columnName
92 for member in cMembers(prefix, columnName, column, False):
93 print "\t%(type)s%(name)s;%(comment)s" % member
97 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
98 for columnName in sorted(table.columns)]
99 + ["%s_N_COLUMNS" % structName.upper()])
102 for columnName in table.columns:
103 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
105 'S': structName.upper(),
107 'C': columnName.upper()}
109 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
112 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
113 const struct %(s)s *%(s)s_next(const struct %(s)s *);
114 #define %(S)s_FOR_EACH(ROW, IDL) \\
115 for ((ROW) = %(s)s_first(IDL); \\
117 (ROW) = %(s)s_next(ROW))
118 #define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
119 for ((ROW) = %(s)s_first(IDL); \\
120 (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
123 void %(s)s_init(struct %(s)s *);
124 void %(s)s_delete(const struct %(s)s *);
125 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
126 ''' % {'s': structName, 'S': structName.upper()}
128 for columnName, column in sorted(table.columns.iteritems()):
129 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
132 /* Functions for fetching columns as \"struct ovsdb_datum\"s. (This is
133 rarely useful. More often, it is easier to access columns by using
134 the members of %(s)s directly.) */""" % {'s': structName}
135 for columnName, column in sorted(table.columns.iteritems()):
136 if column.type.value:
137 valueParam = ', enum ovsdb_atomic_type value_type'
140 print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
141 's': structName, 'c': columnName, 'v': valueParam}
144 for columnName, column in sorted(table.columns.iteritems()):
145 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
146 if column.type.is_smap():
147 args = ['const struct smap *']
149 args = ['%(type)s%(name)s' % member for member
150 in cMembers(prefix, columnName, column, True)]
151 print '%s);' % ', '.join(args)
156 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
158 for tableName in schema.tables:
159 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
162 't': tableName.lower(),
163 'T': tableName.upper()}
164 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
166 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
167 print "\nvoid %sinit(void);" % prefix
168 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
170 def printEnum(members):
171 if len(members) == 0:
175 for member in members[:-1]:
176 print " %s," % member
177 print " %s" % members[-1]
180 def printCIDLSource(schemaFile):
181 schema = parseSchema(schemaFile)
182 prefix = schema.idlPrefix
184 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
189 #include "ovsdb-data.h"
190 #include "ovsdb-error.h"
194 /* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
195 enum { sizeof_bool = 1 };
197 enum { sizeof_bool = sizeof(bool) };
201 ''' % schema.idlHeader
204 for tableName, table in sorted(schema.tables.iteritems()):
205 structName = "%s%s" % (prefix, tableName.lower())
207 static struct %(s)s *
208 %(s)s_cast(const struct ovsdb_idl_row *row)
210 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
212 ''' % {'s': structName}
215 for tableName, table in sorted(schema.tables.iteritems()):
216 structName = "%s%s" % (prefix, tableName.lower())
218 print "/* %s table. */" % (tableName)
221 for columnName, column in sorted(table.columns.iteritems()):
224 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
226 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
230 keyVar = "row->key_%s" % columnName
231 valueVar = "row->value_%s" % columnName
233 keyVar = "row->%s" % columnName
239 print " ovs_assert(inited);"
240 print " smap_init(&row->%s);" % columnName
241 print " for (i = 0; i < datum->n; i++) {"
242 print " smap_add(&row->%s," % columnName
243 print " datum->keys[i].string,"
244 print " datum->values[i].string);"
246 elif (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
248 print " ovs_assert(inited);"
249 print " if (datum->n >= 1) {"
250 if not type.key.ref_table:
251 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
253 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())
256 if type.value.ref_table:
257 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
259 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())
261 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
263 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
266 if type.n_max != sys.maxint:
267 print " size_t n = MIN(%d, datum->n);" % type.n_max
273 print " ovs_assert(inited);"
274 print " %s = NULL;" % keyVar
276 print " %s = NULL;" % valueVar
277 print " row->n_%s = 0;" % columnName
278 print " for (i = 0; i < %s; i++) {" % nMax
280 if type.key.ref_table:
281 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())
283 refs.append('keyRow')
285 keySrc = "datum->keys[i].%s" % type.key.type.to_string()
286 if type.value and type.value.ref_table:
287 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())
288 valueSrc = "valueRow"
289 refs.append('valueRow')
291 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
293 print " if (%s) {" % ' && '.join(refs)
297 print "%sif (!row->n_%s) {" % (indent, columnName)
299 # Special case for boolean types. This is only here because
300 # sparse does not like the "normal" case ("warning: expression
301 # using sizeof bool").
302 if type.key.type == ovs.db.types.BooleanType:
303 sizeof = "sizeof_bool"
305 sizeof = "sizeof *%s" % keyVar
306 print "%s %s = xmalloc(%s * %s);" % (indent, keyVar, nMax,
309 # Special case for boolean types (see above).
310 if type.value.type == ovs.db.types.BooleanType:
311 sizeof = " * sizeof_bool"
313 sizeof = "sizeof *%s" % valueVar
314 print "%s %s = xmalloc(%s * %s);" % (indent, valueVar,
317 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
319 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
320 print "%srow->n_%s++;" % (indent, columnName)
327 for columnName, column in sorted(table.columns.iteritems()):
329 if type.is_smap() or (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
332 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
334 struct %(s)s *row = %(s)s_cast(row_);
336 ovs_assert(inited);''' % {'s': structName, 'c': columnName}
339 print " smap_destroy(&row->%s);" % columnName
342 keyVar = "row->key_%s" % columnName
343 valueVar = "row->value_%s" % columnName
345 keyVar = "row->%s" % columnName
347 print " free(%s);" % keyVar
349 print " free(%s);" % valueVar
354 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
357 }''' % {'s': structName, 'c': columnName}
359 # Generic Row Initialization function.
362 %(s)s_init__(struct ovsdb_idl_row *row)
364 %(s)s_init(%(s)s_cast(row));
365 }""" % {'s': structName}
367 # Row Initialization function.
370 %(s)s_init(struct %(s)s *row)
372 memset(row, 0, sizeof *row); """ % {'s': structName}
373 for columnName, column in sorted(table.columns.iteritems()):
374 if column.type.is_smap():
375 print " smap_init(&row->%s);" % columnName
378 # First, next functions.
381 %(s)s_first(const struct ovsdb_idl *idl)
383 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
387 %(s)s_next(const struct %(s)s *row)
389 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
390 }''' % {'s': structName,
393 'T': tableName.upper()}
397 %(s)s_delete(const struct %(s)s *row)
399 ovsdb_idl_txn_delete(&row->header_);
403 %(s)s_insert(struct ovsdb_idl_txn *txn)
405 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
407 ''' % {'s': structName,
410 'T': tableName.upper()}
413 for columnName, column in sorted(table.columns.iteritems()):
416 %(s)s_verify_%(c)s(const struct %(s)s *row)
419 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
420 }''' % {'s': structName,
421 'S': structName.upper(),
423 'C': columnName.upper()}
426 for columnName, column in sorted(table.columns.iteritems()):
427 if column.type.value:
428 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
429 valueType = '\n ovs_assert(value_type == %s);' % column.type.value.toAtomicType()
430 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
436 /* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
437 * This is useful occasionally: for example, ovsdb_datum_find_key() is an
438 * easier and more efficient way to search for a given key than implementing
439 * the same operation on the "cooked" form in 'row'.
441 * 'key_type' must be %(kt)s.%(vc)s
442 * (This helps to avoid silent bugs if someone changes %(c)s's
443 * type without updating the caller.)
445 * The caller must not modify or free the returned value.
447 * Various kinds of changes can invalidate the returned value: modifying
448 * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
449 * If the returned value is needed for a long time, it is best to make a copy
450 * of it with ovsdb_datum_clone(). */
451 const struct ovsdb_datum *
452 %(s)s_get_%(c)s(const struct %(s)s *row,
453 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
455 ovs_assert(key_type == %(kt)s);%(vt)s
456 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
457 }""" % {'s': structName, 'c': columnName,
458 'kt': column.type.key.toAtomicType(),
459 'v': valueParam, 'vt': valueType, 'vc': valueComment}
462 for columnName, column in sorted(table.columns.iteritems()):
468 %(s)s_set_%(c)s(const struct %(s)s *row, const struct smap *smap)
470 struct ovsdb_datum datum;
474 struct smap_node *node;
477 datum.n = smap_count(smap);
478 datum.keys = xmalloc(datum.n * sizeof *datum.keys);
479 datum.values = xmalloc(datum.n * sizeof *datum.values);
482 SMAP_FOR_EACH (node, smap) {
483 datum.keys[i].string = xstrdup(node->key);
484 datum.values[i].string = xstrdup(node->value);
487 ovsdb_datum_sort_unique(&datum, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
489 ovsdb_datum_init_empty(&datum);
491 ovsdb_idl_txn_write(&row->header_,
492 &%(s)s_columns[%(S)s_COL_%(C)s],
495 """ % {'s': structName,
496 'S': structName.upper(),
498 'C': columnName.upper()}
503 members = cMembers(prefix, columnName, column, True)
504 keyVar = members[0]['name']
508 valueVar = members[1]['name']
510 nVar = members[2]['name']
513 nVar = members[1]['name']
514 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
515 {'s': structName, 'c': columnName,
516 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
518 print " struct ovsdb_datum datum;"
519 if type.n_min == 1 and type.n_max == 1:
521 print " ovs_assert(inited);"
522 print " datum.n = 1;"
523 print " datum.keys = xmalloc(sizeof *datum.keys);"
524 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
526 print " datum.values = xmalloc(sizeof *datum.values);"
527 print " "+ type.value.copyCValue("datum.values[0].%s" % type.value.type.to_string(), valueVar)
529 print " datum.values = NULL;"
530 elif type.is_optional_pointer():
532 print " ovs_assert(inited);"
533 print " if (%s) {" % keyVar
534 print " datum.n = 1;"
535 print " datum.keys = xmalloc(sizeof *datum.keys);"
536 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
538 print " datum.n = 0;"
539 print " datum.keys = NULL;"
541 print " datum.values = NULL;"
545 print " ovs_assert(inited);"
546 print " datum.n = %s;" % nVar
547 print " datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
549 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
551 print " datum.values = NULL;"
552 print " for (i = 0; i < %s; i++) {" % nVar
553 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
555 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
558 valueType = type.value.toAtomicType()
560 valueType = "OVSDB_TYPE_VOID"
561 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
562 type.key.toAtomicType(), valueType)
563 print " ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
565 'S': structName.upper(),
566 'C': columnName.upper()}
570 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
571 structName, structName.upper())
573 static void\n%s_columns_init(void)
575 struct ovsdb_idl_column *c;\
577 for columnName, column in sorted(table.columns.iteritems()):
578 cs = "%s_col_%s" % (structName, columnName)
579 d = {'cs': cs, 'c': columnName, 's': structName}
585 print " /* Initialize %(cs)s. */" % d
586 print " c = &%(cs)s;" % d
587 print " c->name = \"%(c)s\";" % d
588 print column.type.cInitType(" ", "c->type")
589 print " c->mutable = %s;" % mutable
590 print " c->parse = %(s)s_parse_%(c)s;" % d
591 print " c->unparse = %(s)s_unparse_%(c)s;" % d
596 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
597 for tableName, table in sorted(schema.tables.iteritems()):
598 structName = "%s%s" % (prefix, tableName.lower())
603 print " {\"%s\", %s," % (tableName, is_root)
604 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
605 structName, structName)
606 print " sizeof(struct %s), %s_init__}," % (structName, structName)
610 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
611 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
612 schema.name, prefix, prefix)
615 # global init function
625 for tableName, table in sorted(schema.tables.iteritems()):
626 structName = "%s%s" % (prefix, tableName.lower())
627 print " %s_columns_init();" % structName
631 def ovsdb_escape(string):
635 raise ovs.db.error.Error("strings may not contain null bytes")
649 return '\\x%02x' % ord(c)
650 return re.sub(r'["\\\000-\037]', escape, string)
654 %(argv0)s: ovsdb schema compiler
655 usage: %(argv0)s [OPTIONS] COMMAND ARG...
657 The following commands are supported:
658 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
659 c-idl-header IDL print C header file for IDL
660 c-idl-source IDL print C source file for IDL implementation
661 nroff IDL print schema documentation in nroff format
663 The following options are also available:
664 -h, --help display this help message
665 -V, --version display version information\
666 """ % {'argv0': argv0}
669 if __name__ == "__main__":
672 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
676 except getopt.GetoptError, geo:
677 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
680 for key, value in options:
681 if key in ['-h', '--help']:
683 elif key in ['-V', '--version']:
684 print "ovsdb-idlc (Open vSwitch) @VERSION@"
685 elif key in ['-C', '--directory']:
690 optKeys = [key for key, value in options]
693 sys.stderr.write("%s: missing command argument "
694 "(use --help for help)\n" % argv0)
697 commands = {"annotate": (annotateSchema, 2),
698 "c-idl-header": (printCIDLHeader, 1),
699 "c-idl-source": (printCIDLSource, 1)}
701 if not args[0] in commands:
702 sys.stderr.write("%s: unknown command \"%s\" "
703 "(use --help for help)\n" % (argv0, args[0]))
706 func, n_args = commands[args[0]]
707 if len(args) - 1 != n_args:
708 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
710 % (argv0, args[0], n_args, len(args) - 1))
714 except ovs.db.error.Error, e:
715 sys.stderr.write("%s: %s\n" % (argv0, e))