8 sys.path.insert(0, "@abs_top_srcdir@/ovsdb")
9 import simplejson as json
13 class Error(Exception):
14 def __init__(self, msg):
15 Exception.__init__(self)
18 def getMember(json, name, validTypes, description, default=None):
21 if len(validTypes) and type(member) not in validTypes:
22 raise Error("%s: type mismatch for '%s' member"
23 % (description, name))
27 def mustGetMember(json, name, expectedType, description):
28 member = getMember(json, name, expectedType, description)
30 raise Error("%s: missing '%s' member" % (description, name))
34 def __init__(self, name, comment, tables, idlPrefix, idlHeader):
36 self.comment = comment
38 self.idlPrefix = idlPrefix
39 self.idlHeader = idlHeader
43 name = mustGetMember(json, 'name', [unicode], 'database')
44 comment = getMember(json, 'comment', [unicode], 'database')
45 tablesJson = mustGetMember(json, 'tables', [dict], 'database')
47 for tableName, tableJson in tablesJson.iteritems():
48 tables[tableName] = TableSchema.fromJson(tableJson,
49 "%s table" % tableName)
50 idlPrefix = mustGetMember(json, 'idlPrefix', [unicode], 'database')
51 idlHeader = mustGetMember(json, 'idlHeader', [unicode], 'database')
52 return DbSchema(name, comment, tables, idlPrefix, idlHeader)
55 def __init__(self, comment, columns):
56 self.comment = comment
57 self.columns = columns
60 def fromJson(json, description):
61 comment = getMember(json, 'comment', [unicode], description)
62 columnsJson = mustGetMember(json, 'columns', [dict], description)
64 for name, json in columnsJson.iteritems():
65 columns[name] = ColumnSchema.fromJson(
66 json, "column %s in %s" % (name, description))
67 return TableSchema(comment, columns)
70 def __init__(self, comment, type, persistent):
71 self.comment = comment
73 self.persistent = persistent
76 def fromJson(json, description):
77 comment = getMember(json, 'comment', [unicode], description)
78 type = Type.fromJson(mustGetMember(json, 'type', [dict, unicode],
80 'type of %s' % description)
81 ephemeral = getMember(json, 'ephemeral', [bool], description)
82 persistent = ephemeral != True
83 return ColumnSchema(comment, type, persistent)
85 def escapeCString(src):
106 dst += '\\%03o' % ord(c)
113 uuidRE = re.compile("^(%s{8})-(%s{4})-(%s{4})-(%s{4})-(%s{4})(%s{8})$"
114 % (x, x, x, x, x, x))
116 def __init__(self, value):
121 if not uuidRE.match(s):
122 raise Error("%s is not a valid UUID" % s)
127 if UUID.isValidJson(json):
130 raise Error("%s is not valid JSON for a UUID" % json)
133 def isValidJson(json):
134 return len(json) == 2 and json[0] == "uuid" and uuidRE.match(json[1])
137 return ["uuid", self.value]
139 def cInitUUID(self, var):
140 m = re.match(self.value)
141 return ["%s.parts[0] = 0x%s;" % (var, m.group(1)),
142 "%s.parts[1] = 0x%s%s;" % (var, m.group(2), m.group(3)),
143 "%s.parts[2] = 0x%s%s;" % (var, m.group(4), m.group(5)),
144 "%s.parts[3] = 0x%s;" % (var, m.group(6))]
147 def __init__(self, type, value):
152 def fromJson(type_, json):
153 if ((type_ == 'integer' and type(json) in [int, long])
154 or (type_ == 'real' and type(json) in [int, long, float])
155 or (type_ == 'boolean' and json in [True, False])
156 or (type_ == 'string' and type(json) in [str, unicode])):
157 return Atom(type_, json)
158 elif type_ == 'uuid':
159 return UUID.fromJson(json)
161 raise Error("%s is not valid JSON for type %s" % (json, type_))
164 if self.type == 'uuid':
165 return self.value.toString()
169 def cInitAtom(self, var):
170 if self.type == 'integer':
171 return ['%s.integer = %d;' % (var, self.value)]
172 elif self.type == 'real':
173 return ['%s.real = %.15g;' % (var, self.value)]
174 elif self.type == 'boolean':
176 return ['%s.boolean = true;']
178 return ['%s.boolean = false;']
179 elif self.type == 'string':
180 return ['%s.string = xstrdup("%s");'
181 % (var, escapeCString(self.value))]
182 elif self.type == 'uuid':
183 return self.value.cInitUUID(var)
186 def __init__(self, type,
189 minInteger=None, maxInteger=None,
190 minReal=None, maxReal=None,
191 minLength=None, maxLength=None):
194 self.refTable = refTable
195 self.minInteger = minInteger
196 self.maxInteger = maxInteger
197 self.minReal = minReal
198 self.maxReal = maxReal
199 self.minLength = minLength
200 self.maxLength = maxLength
203 def fromJson(json, description):
204 if type(json) == unicode:
205 return BaseType(json)
207 atomicType = mustGetMember(json, 'type', [unicode], description)
208 enum = getMember(json, 'enum', [], description)
210 enumType = Type(atomicType, None, 0, 'unlimited')
211 enum = Datum.fromJson(enumType, enum)
212 refTable = getMember(json, 'refTable', [unicode], description)
213 minInteger = getMember(json, 'minInteger', [int, long], description)
214 maxInteger = getMember(json, 'maxInteger', [int, long], description)
215 minReal = getMember(json, 'minReal', [int, long, float], description)
216 maxReal = getMember(json, 'maxReal', [int, long, float], description)
217 minLength = getMember(json, 'minLength', [int], description)
218 maxLength = getMember(json, 'minLength', [int], description)
219 return BaseType(atomicType, enum, refTable, minInteger, maxInteger, minReal, maxReal, minLength, maxLength)
222 if self.type == 'uuid' and self.refTable:
227 def toCType(self, prefix):
229 return "struct %s%s *" % (prefix, self.refTable.lower())
231 return {'integer': 'int64_t ',
233 'uuid': 'struct uuid ',
235 'string': 'char *'}[self.type]
237 def copyCValue(self, dst, src):
238 args = {'dst': dst, 'src': src}
240 return ("%(dst)s = %(src)s->header_.uuid;") % args
241 elif self.type == 'string':
242 return "%(dst)s = xstrdup(%(src)s);" % args
244 return "%(dst)s = %(src)s;" % args
246 def initCDefault(self, var, isOptional):
248 return "%s = NULL;" % var
249 elif self.type == 'string' and not isOptional:
250 return "%s = \"\";" % var
252 return {'integer': '%s = 0;',
254 'uuid': 'uuid_zero(&%s);',
255 'boolean': '%s = false;',
256 'string': '%s = NULL;'}[self.type] % var
258 def cInitBaseType(self, indent, var):
260 stmts.append('ovsdb_base_type_init(&%s, OVSDB_TYPE_%s);' % (
261 var, self.type.upper()),)
263 stmts.append("%s.enum_ = xmalloc(sizeof *%s.enum_);"
265 stmts += self.enum.cInitDatum("%s.enum_" % var)
266 if self.type == 'integer':
267 if self.minInteger != None:
268 stmts.append('%s.u.integer.min = %d;' % (var, self.minInteger))
269 if self.maxInteger != None:
270 stmts.append('%s.u.integer.max = %d;' % (var, self.maxInteger))
271 elif self.type == 'real':
272 if self.minReal != None:
273 stmts.append('%s.u.real.min = %d;' % (var, self.minReal))
274 if self.maxReal != None:
275 stmts.append('%s.u.real.max = %d;' % (var, self.maxReal))
276 elif self.type == 'string':
277 if self.minLength != None:
278 stmts.append('%s.u.string.minLen = %d;' % (var, self.minLength))
279 if self.maxLength != None:
280 stmts.append('%s.u.string.maxLen = %d;' % (var, self.maxLength))
281 elif self.type == 'uuid':
282 if self.refTable != None:
283 stmts.append('%s.u.uuid.refTableName = "%s";' % (var, escapeCString(self.refTable)))
284 return '\n'.join([indent + stmt for stmt in stmts])
287 def __init__(self, key, value=None, min=1, max=1):
294 def fromJson(json, description):
295 if type(json) == unicode:
296 return Type(BaseType(json))
298 keyJson = mustGetMember(json, 'key', [dict, unicode], description)
299 key = BaseType.fromJson(keyJson, 'key in %s' % description)
301 valueJson = getMember(json, 'value', [dict, unicode], description)
303 value = BaseType.fromJson(valueJson,
304 'value in %s' % description)
308 min = getMember(json, 'min', [int], description, 1)
309 max = getMember(json, 'max', [int, unicode], description, 1)
310 return Type(key, value, min, max)
313 return self.min == 1 and self.max == 1 and not self.value
315 def isOptional(self):
316 return self.min == 0 and self.max == 1
318 def isOptionalPointer(self):
319 return (self.min == 0 and self.max == 1 and not self.value
320 and (self.key.type == 'string' or self.key.refTable))
323 keyName = self.key.toEnglish()
325 valueName = self.value.toEnglish()
329 elif self.isOptional():
331 return "optional %s-%s pair" % (keyName, valueName)
333 return "optional %s" % keyName
335 if self.max == "unlimited":
337 quantity = "%d or more " % self.min
341 quantity = "%d to %d " % (self.min, self.max)
343 quantity = "up to %d " % self.max
346 return "map of %s%s-%s pairs" % (quantity, keyName, valueName)
348 return "set of %s%s" % (quantity, keyName)
350 def cDeclComment(self):
351 if self.min == 1 and self.max == 1 and self.key.type == "string":
352 return "\t/* Always nonnull. */"
356 def cInitType(self, indent, var):
357 initKey = self.key.cInitBaseType(indent, "%s.key" % var)
359 initValue = self.value.cInitBaseType(indent, "%s.value" % var)
361 initValue = ('%sovsdb_base_type_init(&%s.value, '
362 'OVSDB_TYPE_VOID);' % (indent, var))
363 initMin = "%s%s.n_min = %s;" % (indent, var, self.min)
364 if self.max == "unlimited":
368 initMax = "%s%s.n_max = %s;" % (indent, var, max)
369 return "\n".join((initKey, initValue, initMin, initMax))
372 def __init__(self, type, values):
377 def fromJson(type_, json):
379 if len(json) == 2 and json[0] == "set":
381 for atomJson in json[1]:
382 values += [Atom.fromJson(type_.key, atomJson)]
384 values = [Atom.fromJson(type_.key, json)]
386 if len(json) != 2 or json[0] != "map":
387 raise Error("%s is not valid JSON for a map" % json)
389 for pairJson in json[1]:
390 values += [(Atom.fromJson(type_.key, pairJson[0]),
391 Atom.fromJson(type_.value, pairJson[1]))]
392 return Datum(type_, values)
394 def cInitDatum(self, var):
395 if len(self.values) == 0:
396 return ["ovsdb_datum_init_empty(%s);" % var]
398 s = ["%s->n = %d;" % (var, len(self.values))]
399 s += ["%s->keys = xmalloc(%d * sizeof *%s->keys);"
400 % (var, len(self.values), var)]
402 for i in range(len(self.values)):
406 s += key.cInitAtom("%s->keys[%d]" % (var, i))
409 s += ["%s->values = xmalloc(%d * sizeof *%s->values);"
410 % (var, len(self.values), var)]
411 for i in range(len(self.values)):
412 value = self.values[i][1]
413 s += key.cInitAtom("%s->values[%d]" % (var, i))
415 s += ["%s->values = NULL;" % var]
417 if len(self.values) > 1:
418 s += ["ovsdb_datum_sort_assert(%s, OVSDB_TYPE_%s);"
419 % (var, self.type.key.upper())]
423 def parseSchema(filename):
424 return DbSchema.fromJson(json.load(open(filename, "r")))
426 def annotateSchema(schemaFile, annotationFile):
427 schemaJson = json.load(open(schemaFile, "r"))
428 execfile(annotationFile, globals(), {"s": schemaJson})
429 json.dump(schemaJson, sys.stdout)
431 def constify(cType, const):
433 and cType.endswith('*') and not cType.endswith('**')
434 and (cType.startswith('struct uuid') or cType.startswith('char'))):
435 return 'const %s' % cType
439 def cMembers(prefix, columnName, column, const):
441 if type.min == 1 and type.max == 1:
446 if type.isOptionalPointer():
452 key = {'name': "key_%s" % columnName,
453 'type': constify(type.key.toCType(prefix) + pointer, const),
455 value = {'name': "value_%s" % columnName,
456 'type': constify(type.value.toCType(prefix) + pointer, const),
458 members = [key, value]
460 m = {'name': columnName,
461 'type': constify(type.key.toCType(prefix) + pointer, const),
462 'comment': type.cDeclComment()}
465 if not singleton and not type.isOptionalPointer():
466 members.append({'name': 'n_%s' % columnName,
471 def printCIDLHeader(schemaFile):
472 schema = parseSchema(schemaFile)
473 prefix = schema.idlPrefix
475 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
477 #ifndef %(prefix)sIDL_HEADER
478 #define %(prefix)sIDL_HEADER 1
483 #include "ovsdb-idl-provider.h"
484 #include "uuid.h"''' % {'prefix': prefix.upper()}
486 for tableName, table in sorted(schema.tables.iteritems()):
487 structName = "%s%s" % (prefix, tableName.lower())
490 print "/* %s table. */" % tableName
491 print "struct %s {" % structName
492 print "\tstruct ovsdb_idl_row header_;"
493 for columnName, column in sorted(table.columns.iteritems()):
494 print "\n\t/* %s column. */" % columnName
495 for member in cMembers(prefix, columnName, column, False):
496 print "\t%(type)s%(name)s;%(comment)s" % member
500 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
501 for columnName in sorted(table.columns)]
502 + ["%s_N_COLUMNS" % structName.upper()])
505 for columnName in table.columns:
506 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
508 'S': structName.upper(),
510 'C': columnName.upper()}
512 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
515 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
516 const struct %(s)s *%(s)s_next(const struct %(s)s *);
517 #define %(S)s_FOR_EACH(ROW, IDL) for ((ROW) = %(s)s_first(IDL); (ROW); (ROW) = %(s)s_next(ROW))
519 void %(s)s_delete(const struct %(s)s *);
520 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
521 ''' % {'s': structName, 'S': structName.upper()}
523 for columnName, column in sorted(table.columns.iteritems()):
524 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
527 for columnName, column in sorted(table.columns.iteritems()):
529 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
530 args = ['%(type)s%(name)s' % member for member
531 in cMembers(prefix, columnName, column, True)]
532 print '%s);' % ', '.join(args)
535 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
537 for tableName in schema.tables:
538 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
541 't': tableName.lower(),
542 'T': tableName.upper()}
543 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
545 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
546 print "\nvoid %sinit(void);" % prefix
547 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
549 def printEnum(members):
550 if len(members) == 0:
554 for member in members[:-1]:
555 print " %s," % member
556 print " %s" % members[-1]
559 def printCIDLSource(schemaFile):
560 schema = parseSchema(schemaFile)
561 prefix = schema.idlPrefix
563 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
569 #include "ovsdb-data.h"
570 #include "ovsdb-error.h"
573 ''' % schema.idlHeader
576 for tableName, table in sorted(schema.tables.iteritems()):
577 structName = "%s%s" % (prefix, tableName.lower())
579 static struct %(s)s *
580 %(s)s_cast(const struct ovsdb_idl_row *row)
582 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
584 ''' % {'s': structName}
587 for tableName, table in sorted(schema.tables.iteritems()):
588 structName = "%s%s" % (prefix, tableName.lower())
590 if table.comment != None:
591 print "/* %s table (%s). */" % (tableName, table.comment)
593 print "/* %s table. */" % (tableName)
596 for columnName, column in sorted(table.columns.iteritems()):
599 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
601 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
606 keyVar = "row->key_%s" % columnName
607 valueVar = "row->value_%s" % columnName
609 keyVar = "row->%s" % columnName
612 if (type.min == 1 and type.max == 1) or type.isOptionalPointer():
614 print " assert(inited);"
615 print " if (datum->n >= 1) {"
616 if not type.key.refTable:
617 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type)
619 print " %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid));" % (keyVar, prefix, type.key.refTable.lower(), prefix, prefix.upper(), type.key.refTable.upper())
622 if type.value.refTable:
623 print " %s = datum->values[0].%s;" % (valueVar, type.value.type)
625 print " %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid));" % (valueVar, prefix, type.value.refTable.lower(), prefix, prefix.upper(), type.value.refTable.upper())
627 print " %s" % type.key.initCDefault(keyVar, type.min == 0)
629 print " %s" % type.value.initCDefault(valueVar, type.min == 0)
632 if type.max != 'unlimited':
633 print " size_t n = MIN(%d, datum->n);" % type.max
639 print " assert(inited);"
640 print " %s = NULL;" % keyVar
642 print " %s = NULL;" % valueVar
643 print " row->n_%s = 0;" % columnName
644 print " for (i = 0; i < %s; i++) {" % nMax
646 if type.key.refTable:
647 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.refTable.lower(), prefix, type.key.refTable.lower(), prefix, prefix.upper(), type.key.refTable.upper())
649 refs.append('keyRow')
651 keySrc = "datum->keys[i].%s" % type.key.type
652 if type.value and type.value.refTable:
653 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.refTable.lower(), prefix, type.value.refTable.lower(), prefix, prefix.upper(), type.value.refTable.upper())
654 valueSrc = "valueRow"
655 refs.append('valueRow')
657 valueSrc = "datum->values[i].%s" % type.value.type
659 print " if (%s) {" % ' && '.join(refs)
663 print "%sif (!row->n_%s) {" % (indent, columnName)
664 print "%s %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
666 print "%s %s = xmalloc(%s * sizeof %s);" % (indent, valueVar, nMax, valueVar)
668 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
670 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
671 print "%srow->n_%s++;" % (indent, columnName)
678 for columnName, column in sorted(table.columns.iteritems()):
680 if (type.min != 1 or type.max != 1) and not type.isOptionalPointer():
683 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
685 struct %(s)s *row = %(s)s_cast(row_);
687 assert(inited);''' % {'s': structName, 'c': columnName}
689 keyVar = "row->key_%s" % columnName
690 valueVar = "row->value_%s" % columnName
692 keyVar = "row->%s" % columnName
694 print " free(%s);" % keyVar
696 print " free(%s);" % valueVar
701 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
704 }''' % {'s': structName, 'c': columnName}
706 # First, next functions.
709 %(s)s_first(const struct ovsdb_idl *idl)
711 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
715 %(s)s_next(const struct %(s)s *row)
717 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
718 }''' % {'s': structName,
721 'T': tableName.upper()}
725 %(s)s_delete(const struct %(s)s *row)
727 ovsdb_idl_txn_delete(&row->header_);
731 %(s)s_insert(struct ovsdb_idl_txn *txn)
733 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
735 ''' % {'s': structName,
738 'T': tableName.upper()}
741 for columnName, column in sorted(table.columns.iteritems()):
744 %(s)s_verify_%(c)s(const struct %(s)s *row)
747 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
748 }''' % {'s': structName,
749 'S': structName.upper(),
751 'C': columnName.upper()}
754 for columnName, column in sorted(table.columns.iteritems()):
757 members = cMembers(prefix, columnName, column, True)
758 keyVar = members[0]['name']
762 valueVar = members[1]['name']
764 nVar = members[2]['name']
767 nVar = members[1]['name']
768 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
769 {'s': structName, 'c': columnName,
770 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
772 print " struct ovsdb_datum datum;"
773 if type.min == 1 and type.max == 1:
775 print " assert(inited);"
776 print " datum.n = 1;"
777 print " datum.keys = xmalloc(sizeof *datum.keys);"
778 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type, keyVar)
780 print " datum.values = xmalloc(sizeof *datum.values);"
781 print " "+ type.value.copyCValue("datum.values[0].%s" % type.value.type, valueVar)
783 print " datum.values = NULL;"
784 elif type.isOptionalPointer():
786 print " assert(inited);"
787 print " if (%s) {" % keyVar
788 print " datum.n = 1;"
789 print " datum.keys = xmalloc(sizeof *datum.keys);"
790 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type, keyVar)
792 print " datum.n = 0;"
793 print " datum.keys = NULL;"
795 print " datum.values = NULL;"
799 print " assert(inited);"
800 print " datum.n = %s;" % nVar
801 print " datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
803 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
805 print " datum.values = NULL;"
806 print " for (i = 0; i < %s; i++) {" % nVar
807 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type, "%s[i]" % keyVar)
809 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type, "%s[i]" % valueVar)
811 print " ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
813 'S': structName.upper(),
814 'C': columnName.upper()}
818 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
819 structName, structName.upper())
821 static void\n%s_columns_init(void)
823 struct ovsdb_idl_column *c;\
825 for columnName, column in sorted(table.columns.iteritems()):
826 cs = "%s_col_%s" % (structName, columnName)
827 d = {'cs': cs, 'c': columnName, 's': structName}
829 print " /* Initialize %(cs)s. */" % d
830 print " c = &%(cs)s;" % d
831 print " c->name = \"%(c)s\";" % d
832 print column.type.cInitType(" ", "c->type")
833 print " c->parse = %(s)s_parse_%(c)s;" % d
834 print " c->unparse = %(s)s_unparse_%(c)s;" % d
839 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
840 for tableName, table in sorted(schema.tables.iteritems()):
841 structName = "%s%s" % (prefix, tableName.lower())
842 print " {\"%s\"," % tableName
843 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
844 structName, structName)
845 print " sizeof(struct %s)}," % structName
849 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
850 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
851 schema.name, prefix, prefix)
854 # global init function
864 for tableName, table in sorted(schema.tables.iteritems()):
865 structName = "%s%s" % (prefix, tableName.lower())
866 print " %s_columns_init();" % structName
869 def ovsdb_escape(string):
873 raise Error("strings may not contain null bytes")
887 return '\\x%02x' % ord(c)
888 return re.sub(r'["\\\000-\037]', escape, string)
890 def printDoc(schemaFile):
891 schema = parseSchema(schemaFile)
896 for tableName, table in sorted(schema.tables.iteritems()):
897 title = "%s table" % tableName
900 print '-' * len(title)
904 for columnName, column in sorted(table.columns.iteritems()):
906 print "%s (%s)" % (columnName, column.type.toEnglish())
908 print "\t%s" % column.comment
912 %(argv0)s: ovsdb schema compiler
913 usage: %(argv0)s [OPTIONS] COMMAND ARG...
915 The following commands are supported:
916 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
917 c-idl-header IDL print C header file for IDL
918 c-idl-source IDL print C source file for IDL implementation
919 doc IDL print schema documentation
921 The following options are also available:
922 -h, --help display this help message
923 -V, --version display version information\
924 """ % {'argv0': argv0}
927 if __name__ == "__main__":
930 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
934 except getopt.GetoptError, geo:
935 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
938 for key, value in options:
939 if key in ['-h', '--help']:
941 elif key in ['-V', '--version']:
942 print "ovsdb-idlc (Open vSwitch) @VERSION@"
943 elif key in ['-C', '--directory']:
948 optKeys = [key for key, value in options]
951 sys.stderr.write("%s: missing command argument "
952 "(use --help for help)\n" % argv0)
955 commands = {"annotate": (annotateSchema, 2),
956 "c-idl-header": (printCIDLHeader, 1),
957 "c-idl-source": (printCIDLSource, 1),
958 "doc": (printDoc, 1)}
960 if not args[0] in commands:
961 sys.stderr.write("%s: unknown command \"%s\" "
962 "(use --help for help)\n" % (argv0, args[0]))
965 func, n_args = commands[args[0]]
966 if len(args) - 1 != n_args:
967 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
969 % (argv0, args[0], n_args, len(args) - 1))
974 sys.stderr.write("%s: %s\n" % (argv0, e.msg))