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)
21 sys.stdout.write('\n')
23 def constify(cType, const):
24 if (const and cType.endswith('*') and not cType.endswith('**')):
25 return 'const %s' % cType
29 def cMembers(prefix, columnName, column, const):
33 return [{'name': columnName,
34 'type': 'struct smap ',
37 if type.n_min == 1 and type.n_max == 1:
42 if type.is_optional_pointer():
48 key = {'name': "key_%s" % columnName,
49 'type': constify(type.key.toCType(prefix) + pointer, const),
51 value = {'name': "value_%s" % columnName,
52 'type': constify(type.value.toCType(prefix) + pointer, const),
54 members = [key, value]
56 m = {'name': columnName,
57 'type': constify(type.key.toCType(prefix) + pointer, const),
58 'comment': type.cDeclComment()}
61 if not singleton and not type.is_optional_pointer():
62 members.append({'name': 'n_%s' % columnName,
67 def printCIDLHeader(schemaFile):
68 schema = parseSchema(schemaFile)
69 prefix = schema.idlPrefix
71 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
73 #ifndef %(prefix)sIDL_HEADER
74 #define %(prefix)sIDL_HEADER 1
79 #include "ovsdb-data.h"
80 #include "ovsdb-idl-provider.h"
82 #include "uuid.h"''' % {'prefix': prefix.upper()}
84 for tableName, table in sorted(schema.tables.iteritems()):
85 structName = "%s%s" % (prefix, tableName.lower())
88 print "/* %s table. */" % tableName
89 print "struct %s {" % structName
90 print "\tstruct ovsdb_idl_row header_;"
91 for columnName, column in sorted(table.columns.iteritems()):
92 print "\n\t/* %s column. */" % columnName
93 for member in cMembers(prefix, columnName, column, False):
94 print "\t%(type)s%(name)s;%(comment)s" % member
98 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
99 for columnName in sorted(table.columns)]
100 + ["%s_N_COLUMNS" % structName.upper()])
103 for columnName in table.columns:
104 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
106 'S': structName.upper(),
108 'C': columnName.upper()}
110 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
113 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
114 const struct %(s)s *%(s)s_next(const struct %(s)s *);
115 #define %(S)s_FOR_EACH(ROW, IDL) \\
116 for ((ROW) = %(s)s_first(IDL); \\
118 (ROW) = %(s)s_next(ROW))
119 #define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
120 for ((ROW) = %(s)s_first(IDL); \\
121 (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
124 void %(s)s_init(struct %(s)s *);
125 void %(s)s_delete(const struct %(s)s *);
126 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
127 ''' % {'s': structName, 'S': structName.upper()}
129 for columnName, column in sorted(table.columns.iteritems()):
130 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
133 /* Functions for fetching columns as \"struct ovsdb_datum\"s. (This is
134 rarely useful. More often, it is easier to access columns by using
135 the members of %(s)s directly.) */""" % {'s': structName}
136 for columnName, column in sorted(table.columns.iteritems()):
137 if column.type.value:
138 valueParam = ', enum ovsdb_atomic_type value_type'
141 print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
142 's': structName, 'c': columnName, 'v': valueParam}
145 for columnName, column in sorted(table.columns.iteritems()):
146 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
147 if column.type.is_smap():
148 args = ['const struct smap *']
150 args = ['%(type)s%(name)s' % member for member
151 in cMembers(prefix, columnName, column, True)]
152 print '%s);' % ', '.join(args)
157 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
159 for tableName in schema.tables:
160 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
163 't': tableName.lower(),
164 'T': tableName.upper()}
165 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
167 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
168 print "\nvoid %sinit(void);" % prefix
169 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
171 def printEnum(members):
172 if len(members) == 0:
176 for member in members[:-1]:
177 print " %s," % member
178 print " %s" % members[-1]
181 def printCIDLSource(schemaFile):
182 schema = parseSchema(schemaFile)
183 prefix = schema.idlPrefix
185 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
190 #include "ovsdb-data.h"
191 #include "ovsdb-error.h"
195 /* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
196 enum { sizeof_bool = 1 };
198 enum { sizeof_bool = sizeof(bool) };
202 ''' % schema.idlHeader
205 for tableName, table in sorted(schema.tables.iteritems()):
206 structName = "%s%s" % (prefix, tableName.lower())
208 static struct %(s)s *
209 %(s)s_cast(const struct ovsdb_idl_row *row)
211 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
213 ''' % {'s': structName}
216 for tableName, table in sorted(schema.tables.iteritems()):
217 structName = "%s%s" % (prefix, tableName.lower())
219 print "/* %s table. */" % (tableName)
222 for columnName, column in sorted(table.columns.iteritems()):
225 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
227 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
231 keyVar = "row->key_%s" % columnName
232 valueVar = "row->value_%s" % columnName
234 keyVar = "row->%s" % columnName
240 print " ovs_assert(inited);"
241 print " smap_init(&row->%s);" % columnName
242 print " for (i = 0; i < datum->n; i++) {"
243 print " smap_add(&row->%s," % columnName
244 print " datum->keys[i].string,"
245 print " datum->values[i].string);"
247 elif (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
249 print " ovs_assert(inited);"
250 print " if (datum->n >= 1) {"
251 if not type.key.ref_table:
252 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
254 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())
257 if type.value.ref_table:
258 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
260 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())
262 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
264 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
267 if type.n_max != sys.maxint:
268 print " size_t n = MIN(%d, datum->n);" % type.n_max
274 print " ovs_assert(inited);"
275 print " %s = NULL;" % keyVar
277 print " %s = NULL;" % valueVar
278 print " row->n_%s = 0;" % columnName
279 print " for (i = 0; i < %s; i++) {" % nMax
281 if type.key.ref_table:
282 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())
284 refs.append('keyRow')
286 keySrc = "datum->keys[i].%s" % type.key.type.to_string()
287 if type.value and type.value.ref_table:
288 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())
289 valueSrc = "valueRow"
290 refs.append('valueRow')
292 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
294 print " if (%s) {" % ' && '.join(refs)
298 print "%sif (!row->n_%s) {" % (indent, columnName)
300 # Special case for boolean types. This is only here because
301 # sparse does not like the "normal" case ("warning: expression
302 # using sizeof bool").
303 if type.key.type == ovs.db.types.BooleanType:
304 sizeof = "sizeof_bool"
306 sizeof = "sizeof *%s" % keyVar
307 print "%s %s = xmalloc(%s * %s);" % (indent, keyVar, nMax,
310 # Special case for boolean types (see above).
311 if type.value.type == ovs.db.types.BooleanType:
312 sizeof = " * sizeof_bool"
314 sizeof = "sizeof *%s" % valueVar
315 print "%s %s = xmalloc(%s * %s);" % (indent, valueVar,
318 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
320 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
321 print "%srow->n_%s++;" % (indent, columnName)
328 for columnName, column in sorted(table.columns.iteritems()):
330 if type.is_smap() or (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
333 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
335 struct %(s)s *row = %(s)s_cast(row_);
337 ovs_assert(inited);''' % {'s': structName, 'c': columnName}
340 print " smap_destroy(&row->%s);" % columnName
343 keyVar = "row->key_%s" % columnName
344 valueVar = "row->value_%s" % columnName
346 keyVar = "row->%s" % columnName
348 print " free(%s);" % keyVar
350 print " free(%s);" % valueVar
355 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
358 }''' % {'s': structName, 'c': columnName}
360 # Generic Row Initialization function.
363 %(s)s_init__(struct ovsdb_idl_row *row)
365 %(s)s_init(%(s)s_cast(row));
366 }""" % {'s': structName}
368 # Row Initialization function.
371 %(s)s_init(struct %(s)s *row)
373 memset(row, 0, sizeof *row); """ % {'s': structName}
374 for columnName, column in sorted(table.columns.iteritems()):
375 if column.type.is_smap():
376 print " smap_init(&row->%s);" % columnName
379 # First, next functions.
382 %(s)s_first(const struct ovsdb_idl *idl)
384 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
388 %(s)s_next(const struct %(s)s *row)
390 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
391 }''' % {'s': structName,
394 'T': tableName.upper()}
398 %(s)s_delete(const struct %(s)s *row)
400 ovsdb_idl_txn_delete(&row->header_);
404 %(s)s_insert(struct ovsdb_idl_txn *txn)
406 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
408 ''' % {'s': structName,
411 'T': tableName.upper()}
414 for columnName, column in sorted(table.columns.iteritems()):
417 %(s)s_verify_%(c)s(const struct %(s)s *row)
420 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
421 }''' % {'s': structName,
422 'S': structName.upper(),
424 'C': columnName.upper()}
427 for columnName, column in sorted(table.columns.iteritems()):
428 if column.type.value:
429 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
430 valueType = '\n ovs_assert(value_type == %s);' % column.type.value.toAtomicType()
431 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
437 /* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
438 * This is useful occasionally: for example, ovsdb_datum_find_key() is an
439 * easier and more efficient way to search for a given key than implementing
440 * the same operation on the "cooked" form in 'row'.
442 * 'key_type' must be %(kt)s.%(vc)s
443 * (This helps to avoid silent bugs if someone changes %(c)s's
444 * type without updating the caller.)
446 * The caller must not modify or free the returned value.
448 * Various kinds of changes can invalidate the returned value: modifying
449 * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
450 * If the returned value is needed for a long time, it is best to make a copy
451 * of it with ovsdb_datum_clone(). */
452 const struct ovsdb_datum *
453 %(s)s_get_%(c)s(const struct %(s)s *row,
454 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
456 ovs_assert(key_type == %(kt)s);%(vt)s
457 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
458 }""" % {'s': structName, 'c': columnName,
459 'kt': column.type.key.toAtomicType(),
460 'v': valueParam, 'vt': valueType, 'vc': valueComment}
463 for columnName, column in sorted(table.columns.iteritems()):
469 %(s)s_set_%(c)s(const struct %(s)s *row, const struct smap *smap)
471 struct ovsdb_datum datum;
475 struct smap_node *node;
478 datum.n = smap_count(smap);
479 datum.keys = xmalloc(datum.n * sizeof *datum.keys);
480 datum.values = xmalloc(datum.n * sizeof *datum.values);
483 SMAP_FOR_EACH (node, smap) {
484 datum.keys[i].string = xstrdup(node->key);
485 datum.values[i].string = xstrdup(node->value);
488 ovsdb_datum_sort_unique(&datum, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
490 ovsdb_datum_init_empty(&datum);
492 ovsdb_idl_txn_write(&row->header_,
493 &%(s)s_columns[%(S)s_COL_%(C)s],
496 """ % {'s': structName,
497 'S': structName.upper(),
499 'C': columnName.upper()}
504 members = cMembers(prefix, columnName, column, True)
505 keyVar = members[0]['name']
509 valueVar = members[1]['name']
511 nVar = members[2]['name']
514 nVar = members[1]['name']
515 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
516 {'s': structName, 'c': columnName,
517 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
519 print " struct ovsdb_datum datum;"
520 if type.n_min == 1 and type.n_max == 1:
521 print " union ovsdb_atom key;"
523 print " union ovsdb_atom value;"
525 print " ovs_assert(inited);"
526 print " datum.n = 1;"
527 print " datum.keys = &key;"
528 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
530 print " datum.values = &value;"
531 print " "+ type.value.assign_c_value_casting_away_const("value.%s" % type.value.type.to_string(), valueVar)
533 print " datum.values = NULL;"
534 txn_write_func = "ovsdb_idl_txn_write_clone"
535 elif type.is_optional_pointer():
536 print " union ovsdb_atom key;"
538 print " ovs_assert(inited);"
539 print " if (%s) {" % keyVar
540 print " datum.n = 1;"
541 print " datum.keys = &key;"
542 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
544 print " datum.n = 0;"
545 print " datum.keys = NULL;"
547 print " datum.values = NULL;"
548 txn_write_func = "ovsdb_idl_txn_write_clone"
549 elif type.n_max == 1:
550 print " union ovsdb_atom key;"
552 print " ovs_assert(inited);"
553 print " if (%s) {" % nVar
554 print " datum.n = 1;"
555 print " datum.keys = &key;"
556 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), "*" + keyVar)
558 print " datum.n = 0;"
559 print " datum.keys = NULL;"
561 print " datum.values = NULL;"
562 txn_write_func = "ovsdb_idl_txn_write_clone"
566 print " ovs_assert(inited);"
567 print " datum.n = %s;" % nVar
568 print " datum.keys = %s ? xmalloc(%s * sizeof *datum.keys) : NULL;" % (nVar, nVar)
570 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
572 print " datum.values = NULL;"
573 print " for (i = 0; i < %s; i++) {" % nVar
574 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
576 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
579 valueType = type.value.toAtomicType()
581 valueType = "OVSDB_TYPE_VOID"
582 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
583 type.key.toAtomicType(), valueType)
584 txn_write_func = "ovsdb_idl_txn_write"
585 print " %(f)s(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
586 % {'f': txn_write_func,
588 'S': structName.upper(),
589 'C': columnName.upper()}
593 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
594 structName, structName.upper())
596 static void\n%s_columns_init(void)
598 struct ovsdb_idl_column *c;\
600 for columnName, column in sorted(table.columns.iteritems()):
601 cs = "%s_col_%s" % (structName, columnName)
602 d = {'cs': cs, 'c': columnName, 's': structName}
608 print " /* Initialize %(cs)s. */" % d
609 print " c = &%(cs)s;" % d
610 print " c->name = \"%(c)s\";" % d
611 print column.type.cInitType(" ", "c->type")
612 print " c->mutable = %s;" % mutable
613 print " c->parse = %(s)s_parse_%(c)s;" % d
614 print " c->unparse = %(s)s_unparse_%(c)s;" % d
619 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
620 for tableName, table in sorted(schema.tables.iteritems()):
621 structName = "%s%s" % (prefix, tableName.lower())
626 print " {\"%s\", %s," % (tableName, is_root)
627 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
628 structName, structName)
629 print " sizeof(struct %s), %s_init__}," % (structName, structName)
633 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
634 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
635 schema.name, prefix, prefix)
638 # global init function
648 for tableName, table in sorted(schema.tables.iteritems()):
649 structName = "%s%s" % (prefix, tableName.lower())
650 print " %s_columns_init();" % structName
654 def ovsdb_escape(string):
658 raise ovs.db.error.Error("strings may not contain null bytes")
672 return '\\x%02x' % ord(c)
673 return re.sub(r'["\\\000-\037]', escape, string)
677 %(argv0)s: ovsdb schema compiler
678 usage: %(argv0)s [OPTIONS] COMMAND ARG...
680 The following commands are supported:
681 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
682 c-idl-header IDL print C header file for IDL
683 c-idl-source IDL print C source file for IDL implementation
684 nroff IDL print schema documentation in nroff format
686 The following options are also available:
687 -h, --help display this help message
688 -V, --version display version information\
689 """ % {'argv0': argv0}
692 if __name__ == "__main__":
695 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
699 except getopt.GetoptError, geo:
700 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
703 for key, value in options:
704 if key in ['-h', '--help']:
706 elif key in ['-V', '--version']:
707 print "ovsdb-idlc (Open vSwitch) @VERSION@"
708 elif key in ['-C', '--directory']:
713 optKeys = [key for key, value in options]
716 sys.stderr.write("%s: missing command argument "
717 "(use --help for help)\n" % argv0)
720 commands = {"annotate": (annotateSchema, 2),
721 "c-idl-header": (printCIDLHeader, 1),
722 "c-idl-source": (printCIDLSource, 1)}
724 if not args[0] in commands:
725 sys.stderr.write("%s: unknown command \"%s\" "
726 "(use --help for help)\n" % (argv0, args[0]))
729 func, n_args = commands[args[0]]
730 if len(args) - 1 != n_args:
731 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
733 % (argv0, args[0], n_args, len(args) - 1))
737 except ovs.db.error.Error, e:
738 sys.stderr.write("%s: %s\n" % (argv0, e))