]> git.proxmox.com Git - mirror_ovs.git/blob - ovsdb/ovsdb-idlc.in
ovsdb: Frees database memory on ovsdb process cleanup.
[mirror_ovs.git] / ovsdb / ovsdb-idlc.in
1 #! @PYTHON@
2
3 import getopt
4 import os
5 import re
6 import sys
7
8 import ovs.json
9 import ovs.db.error
10 import ovs.db.schema
11
12 argv0 = sys.argv[0]
13
14 def parseSchema(filename):
15 return ovs.db.schema.IdlSchema.from_json(ovs.json.from_file(filename))
16
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')
22
23 def constify(cType, const):
24 if (const and cType.endswith('*') and not cType.endswith('**')):
25 return 'const %s' % cType
26 else:
27 return cType
28
29 def cMembers(prefix, columnName, column, const):
30 type = column.type
31
32 if type.is_smap():
33 return [{'name': columnName,
34 'type': 'struct smap ',
35 'comment': ''}]
36
37 if type.n_min == 1 and type.n_max == 1:
38 singleton = True
39 pointer = ''
40 else:
41 singleton = False
42 if type.is_optional_pointer():
43 pointer = ''
44 else:
45 pointer = '*'
46
47 if type.value:
48 key = {'name': "key_%s" % columnName,
49 'type': constify(type.key.toCType(prefix) + pointer, const),
50 'comment': ''}
51 value = {'name': "value_%s" % columnName,
52 'type': constify(type.value.toCType(prefix) + pointer, const),
53 'comment': ''}
54 members = [key, value]
55 else:
56 m = {'name': columnName,
57 'type': constify(type.key.toCType(prefix) + pointer, const),
58 'comment': type.cDeclComment()}
59 members = [m]
60
61 if not singleton and not type.is_optional_pointer():
62 members.append({'name': 'n_%s' % columnName,
63 'type': 'size_t ',
64 'comment': ''})
65 return members
66
67 def printCIDLHeader(schemaFile):
68 schema = parseSchema(schemaFile)
69 prefix = schema.idlPrefix
70 print '''\
71 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
72
73 #ifndef %(prefix)sIDL_HEADER
74 #define %(prefix)sIDL_HEADER 1
75
76 #include <stdbool.h>
77 #include <stddef.h>
78 #include <stdint.h>
79 #include "ovsdb-data.h"
80 #include "ovsdb-idl-provider.h"
81 #include "smap.h"
82 #include "uuid.h"''' % {'prefix': prefix.upper()}
83
84 for tableName, table in sorted(schema.tables.iteritems()):
85 structName = "%s%s" % (prefix, tableName.lower())
86
87 print "\f"
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
95 print "};"
96
97 # Column indexes.
98 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
99 for columnName in sorted(table.columns)]
100 + ["%s_N_COLUMNS" % structName.upper()])
101
102 print
103 for columnName in table.columns:
104 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
105 's': structName,
106 'S': structName.upper(),
107 'c': columnName,
108 'C': columnName.upper()}
109
110 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
111
112 print '''
113 const struct %(s)s *%(s)s_get_for_uuid(const struct ovsdb_idl *, const struct uuid *);
114 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
115 const struct %(s)s *%(s)s_next(const struct %(s)s *);
116 #define %(S)s_FOR_EACH(ROW, IDL) \\
117 for ((ROW) = %(s)s_first(IDL); \\
118 (ROW); \\
119 (ROW) = %(s)s_next(ROW))
120 #define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
121 for ((ROW) = %(s)s_first(IDL); \\
122 (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
123 (ROW) = (NEXT))
124
125 void %(s)s_init(struct %(s)s *);
126 void %(s)s_delete(const struct %(s)s *);
127 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
128 ''' % {'s': structName, 'S': structName.upper()}
129
130 for columnName, column in sorted(table.columns.iteritems()):
131 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
132
133 print """
134 /* Functions for fetching columns as \"struct ovsdb_datum\"s. (This is
135 rarely useful. More often, it is easier to access columns by using
136 the members of %(s)s directly.) */""" % {'s': structName}
137 for columnName, column in sorted(table.columns.iteritems()):
138 if column.type.value:
139 valueParam = ', enum ovsdb_atomic_type value_type'
140 else:
141 valueParam = ''
142 print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
143 's': structName, 'c': columnName, 'v': valueParam}
144
145 print
146 for columnName, column in sorted(table.columns.iteritems()):
147 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
148 if column.type.is_smap():
149 args = ['const struct smap *']
150 else:
151 args = ['%(type)s%(name)s' % member for member
152 in cMembers(prefix, columnName, column, True)]
153 print '%s);' % ', '.join(args)
154
155 print
156
157 # Table indexes.
158 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
159 print
160 for tableName in schema.tables:
161 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
162 'p': prefix,
163 'P': prefix.upper(),
164 't': tableName.lower(),
165 'T': tableName.upper()}
166 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
167
168 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
169 print "\nvoid %sinit(void);" % prefix
170
171 print "\nconst char * %sget_db_version(void);" % prefix
172 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
173
174 def printEnum(members):
175 if len(members) == 0:
176 return
177
178 print "\nenum {";
179 for member in members[:-1]:
180 print " %s," % member
181 print " %s" % members[-1]
182 print "};"
183
184 def printCIDLSource(schemaFile):
185 schema = parseSchema(schemaFile)
186 prefix = schema.idlPrefix
187 print '''\
188 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
189
190 #include <config.h>
191 #include %s
192 #include <limits.h>
193 #include "ovs-thread.h"
194 #include "ovsdb-data.h"
195 #include "ovsdb-error.h"
196 #include "util.h"
197
198 #ifdef __CHECKER__
199 /* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
200 enum { sizeof_bool = 1 };
201 #else
202 enum { sizeof_bool = sizeof(bool) };
203 #endif
204
205 static bool inited;
206 ''' % schema.idlHeader
207
208 # Cast functions.
209 for tableName, table in sorted(schema.tables.iteritems()):
210 structName = "%s%s" % (prefix, tableName.lower())
211 print '''
212 static struct %(s)s *
213 %(s)s_cast(const struct ovsdb_idl_row *row)
214 {
215 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
216 }\
217 ''' % {'s': structName}
218
219
220 for tableName, table in sorted(schema.tables.iteritems()):
221 structName = "%s%s" % (prefix, tableName.lower())
222 print "\f"
223 print "/* %s table. */" % (tableName)
224
225 # Parse functions.
226 for columnName, column in sorted(table.columns.iteritems()):
227 print '''
228 static void
229 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
230 {
231 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
232 'c': columnName}
233 type = column.type
234 if type.value:
235 keyVar = "row->key_%s" % columnName
236 valueVar = "row->value_%s" % columnName
237 else:
238 keyVar = "row->%s" % columnName
239 valueVar = None
240
241 if type.is_smap():
242 print " size_t i;"
243 print
244 print " ovs_assert(inited);"
245 print " smap_init(&row->%s);" % columnName
246 print " for (i = 0; i < datum->n; i++) {"
247 print " smap_add(&row->%s," % columnName
248 print " datum->keys[i].string,"
249 print " datum->values[i].string);"
250 print " }"
251 elif (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
252 print
253 print " ovs_assert(inited);"
254 print " if (datum->n >= 1) {"
255 if not type.key.ref_table:
256 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
257 else:
258 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())
259
260 if valueVar:
261 if type.value.ref_table:
262 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
263 else:
264 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())
265 print " } else {"
266 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
267 if valueVar:
268 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
269 print " }"
270 else:
271 if type.n_max != sys.maxint:
272 print " size_t n = MIN(%d, datum->n);" % type.n_max
273 nMax = "n"
274 else:
275 nMax = "datum->n"
276 print " size_t i;"
277 print
278 print " ovs_assert(inited);"
279 print " %s = NULL;" % keyVar
280 if valueVar:
281 print " %s = NULL;" % valueVar
282 print " row->n_%s = 0;" % columnName
283 print " for (i = 0; i < %s; i++) {" % nMax
284 refs = []
285 if type.key.ref_table:
286 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())
287 keySrc = "keyRow"
288 refs.append('keyRow')
289 else:
290 keySrc = "datum->keys[i].%s" % type.key.type.to_string()
291 if type.value and type.value.ref_table:
292 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())
293 valueSrc = "valueRow"
294 refs.append('valueRow')
295 elif valueVar:
296 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
297 if refs:
298 print " if (%s) {" % ' && '.join(refs)
299 indent = " "
300 else:
301 indent = " "
302 print "%sif (!row->n_%s) {" % (indent, columnName)
303
304 # Special case for boolean types. This is only here because
305 # sparse does not like the "normal" case ("warning: expression
306 # using sizeof bool").
307 if type.key.type == ovs.db.types.BooleanType:
308 sizeof = "sizeof_bool"
309 else:
310 sizeof = "sizeof *%s" % keyVar
311 print "%s %s = xmalloc(%s * %s);" % (indent, keyVar, nMax,
312 sizeof)
313 if valueVar:
314 # Special case for boolean types (see above).
315 if type.value.type == ovs.db.types.BooleanType:
316 sizeof = " * sizeof_bool"
317 else:
318 sizeof = "sizeof *%s" % valueVar
319 print "%s %s = xmalloc(%s * %s);" % (indent, valueVar,
320 nMax, sizeof)
321 print "%s}" % indent
322 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
323 if valueVar:
324 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
325 print "%srow->n_%s++;" % (indent, columnName)
326 if refs:
327 print " }"
328 print " }"
329 print "}"
330
331 # Unparse functions.
332 for columnName, column in sorted(table.columns.iteritems()):
333 type = column.type
334 if type.is_smap() or (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
335 print '''
336 static void
337 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
338 {
339 struct %(s)s *row = %(s)s_cast(row_);
340
341 ovs_assert(inited);''' % {'s': structName, 'c': columnName}
342
343 if type.is_smap():
344 print " smap_destroy(&row->%s);" % columnName
345 else:
346 if type.value:
347 keyVar = "row->key_%s" % columnName
348 valueVar = "row->value_%s" % columnName
349 else:
350 keyVar = "row->%s" % columnName
351 valueVar = None
352 print " free(%s);" % keyVar
353 if valueVar:
354 print " free(%s);" % valueVar
355 print '}'
356 else:
357 print '''
358 static void
359 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
360 {
361 /* Nothing to do. */
362 }''' % {'s': structName, 'c': columnName}
363
364 # Generic Row Initialization function.
365 print """
366 static void
367 %(s)s_init__(struct ovsdb_idl_row *row)
368 {
369 %(s)s_init(%(s)s_cast(row));
370 }""" % {'s': structName}
371
372 # Row Initialization function.
373 print """
374 void
375 %(s)s_init(struct %(s)s *row)
376 {
377 memset(row, 0, sizeof *row); """ % {'s': structName}
378 for columnName, column in sorted(table.columns.iteritems()):
379 if column.type.is_smap():
380 print " smap_init(&row->%s);" % columnName
381 print "}"
382
383 # First, next functions.
384 print '''
385 const struct %(s)s *
386 %(s)s_get_for_uuid(const struct ovsdb_idl *idl, const struct uuid *uuid)
387 {
388 return %(s)s_cast(ovsdb_idl_get_row_for_uuid(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s], uuid));
389 }
390
391 const struct %(s)s *
392 %(s)s_first(const struct ovsdb_idl *idl)
393 {
394 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
395 }
396
397 const struct %(s)s *
398 %(s)s_next(const struct %(s)s *row)
399 {
400 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
401 }''' % {'s': structName,
402 'p': prefix,
403 'P': prefix.upper(),
404 'T': tableName.upper()}
405
406 print '''
407 void
408 %(s)s_delete(const struct %(s)s *row)
409 {
410 ovsdb_idl_txn_delete(&row->header_);
411 }
412
413 struct %(s)s *
414 %(s)s_insert(struct ovsdb_idl_txn *txn)
415 {
416 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
417 }
418 ''' % {'s': structName,
419 'p': prefix,
420 'P': prefix.upper(),
421 'T': tableName.upper()}
422
423 # Verify functions.
424 for columnName, column in sorted(table.columns.iteritems()):
425 print '''
426 void
427 %(s)s_verify_%(c)s(const struct %(s)s *row)
428 {
429 ovs_assert(inited);
430 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
431 }''' % {'s': structName,
432 'S': structName.upper(),
433 'c': columnName,
434 'C': columnName.upper()}
435
436 # Get functions.
437 for columnName, column in sorted(table.columns.iteritems()):
438 if column.type.value:
439 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
440 valueType = '\n ovs_assert(value_type == %s);' % column.type.value.toAtomicType()
441 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
442 else:
443 valueParam = ''
444 valueType = ''
445 valueComment = ''
446 print """
447 /* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
448 * This is useful occasionally: for example, ovsdb_datum_find_key() is an
449 * easier and more efficient way to search for a given key than implementing
450 * the same operation on the "cooked" form in 'row'.
451 *
452 * 'key_type' must be %(kt)s.%(vc)s
453 * (This helps to avoid silent bugs if someone changes %(c)s's
454 * type without updating the caller.)
455 *
456 * The caller must not modify or free the returned value.
457 *
458 * Various kinds of changes can invalidate the returned value: modifying
459 * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
460 * If the returned value is needed for a long time, it is best to make a copy
461 * of it with ovsdb_datum_clone(). */
462 const struct ovsdb_datum *
463 %(s)s_get_%(c)s(const struct %(s)s *row,
464 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
465 {
466 ovs_assert(key_type == %(kt)s);%(vt)s
467 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
468 }""" % {'s': structName, 'c': columnName,
469 'kt': column.type.key.toAtomicType(),
470 'v': valueParam, 'vt': valueType, 'vc': valueComment}
471
472 # Set functions.
473 for columnName, column in sorted(table.columns.iteritems()):
474 type = column.type
475
476 if type.is_smap():
477 print """
478 void
479 %(s)s_set_%(c)s(const struct %(s)s *row, const struct smap *smap)
480 {
481 struct ovsdb_datum datum;
482
483 ovs_assert(inited);
484 if (smap) {
485 struct smap_node *node;
486 size_t i;
487
488 datum.n = smap_count(smap);
489 datum.keys = xmalloc(datum.n * sizeof *datum.keys);
490 datum.values = xmalloc(datum.n * sizeof *datum.values);
491
492 i = 0;
493 SMAP_FOR_EACH (node, smap) {
494 datum.keys[i].string = xstrdup(node->key);
495 datum.values[i].string = xstrdup(node->value);
496 i++;
497 }
498 ovsdb_datum_sort_unique(&datum, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
499 } else {
500 ovsdb_datum_init_empty(&datum);
501 }
502 ovsdb_idl_txn_write(&row->header_,
503 &%(s)s_columns[%(S)s_COL_%(C)s],
504 &datum);
505 }
506 """ % {'s': structName,
507 'S': structName.upper(),
508 'c': columnName,
509 'C': columnName.upper()}
510 continue
511
512
513 print '\nvoid'
514 members = cMembers(prefix, columnName, column, True)
515 keyVar = members[0]['name']
516 nVar = None
517 valueVar = None
518 if type.value:
519 valueVar = members[1]['name']
520 if len(members) > 2:
521 nVar = members[2]['name']
522 else:
523 if len(members) > 1:
524 nVar = members[1]['name']
525 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
526 {'s': structName, 'c': columnName,
527 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
528 print "{"
529 print " struct ovsdb_datum datum;"
530 if type.n_min == 1 and type.n_max == 1:
531 print " union ovsdb_atom key;"
532 if type.value:
533 print " union ovsdb_atom value;"
534 print
535 print " ovs_assert(inited);"
536 print " datum.n = 1;"
537 print " datum.keys = &key;"
538 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
539 if type.value:
540 print " datum.values = &value;"
541 print " "+ type.value.assign_c_value_casting_away_const("value.%s" % type.value.type.to_string(), valueVar)
542 else:
543 print " datum.values = NULL;"
544 txn_write_func = "ovsdb_idl_txn_write_clone"
545 elif type.is_optional_pointer():
546 print " union ovsdb_atom key;"
547 print
548 print " ovs_assert(inited);"
549 print " if (%s) {" % keyVar
550 print " datum.n = 1;"
551 print " datum.keys = &key;"
552 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
553 print " } else {"
554 print " datum.n = 0;"
555 print " datum.keys = NULL;"
556 print " }"
557 print " datum.values = NULL;"
558 txn_write_func = "ovsdb_idl_txn_write_clone"
559 elif type.n_max == 1:
560 print " union ovsdb_atom key;"
561 print
562 print " ovs_assert(inited);"
563 print " if (%s) {" % nVar
564 print " datum.n = 1;"
565 print " datum.keys = &key;"
566 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), "*" + keyVar)
567 print " } else {"
568 print " datum.n = 0;"
569 print " datum.keys = NULL;"
570 print " }"
571 print " datum.values = NULL;"
572 txn_write_func = "ovsdb_idl_txn_write_clone"
573 else:
574 print " size_t i;"
575 print
576 print " ovs_assert(inited);"
577 print " datum.n = %s;" % nVar
578 print " datum.keys = %s ? xmalloc(%s * sizeof *datum.keys) : NULL;" % (nVar, nVar)
579 if type.value:
580 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
581 else:
582 print " datum.values = NULL;"
583 print " for (i = 0; i < %s; i++) {" % nVar
584 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
585 if type.value:
586 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
587 print " }"
588 if type.value:
589 valueType = type.value.toAtomicType()
590 else:
591 valueType = "OVSDB_TYPE_VOID"
592 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
593 type.key.toAtomicType(), valueType)
594 txn_write_func = "ovsdb_idl_txn_write"
595 print " %(f)s(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
596 % {'f': txn_write_func,
597 's': structName,
598 'S': structName.upper(),
599 'C': columnName.upper()}
600 print "}"
601
602 # Table columns.
603 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
604 structName, structName.upper())
605 print """
606 static void\n%s_columns_init(void)
607 {
608 struct ovsdb_idl_column *c;\
609 """ % structName
610 for columnName, column in sorted(table.columns.iteritems()):
611 cs = "%s_col_%s" % (structName, columnName)
612 d = {'cs': cs, 'c': columnName, 's': structName}
613 if column.mutable:
614 mutable = "true"
615 else:
616 mutable = "false"
617 print
618 print " /* Initialize %(cs)s. */" % d
619 print " c = &%(cs)s;" % d
620 print " c->name = \"%(c)s\";" % d
621 print column.type.cInitType(" ", "c->type")
622 print " c->mutable = %s;" % mutable
623 print " c->parse = %(s)s_parse_%(c)s;" % d
624 print " c->unparse = %(s)s_unparse_%(c)s;" % d
625 print "}"
626
627 # Table classes.
628 print "\f"
629 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
630 for tableName, table in sorted(schema.tables.iteritems()):
631 structName = "%s%s" % (prefix, tableName.lower())
632 if table.is_root:
633 is_root = "true"
634 else:
635 is_root = "false"
636 print " {\"%s\", %s," % (tableName, is_root)
637 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
638 structName, structName)
639 print " sizeof(struct %s), %s_init__}," % (structName, structName)
640 print "};"
641
642 # IDL class.
643 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
644 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
645 schema.name, prefix, prefix)
646 print "};"
647
648 # global init function
649 print """
650 void
651 %sinit(void)
652 {
653 if (inited) {
654 return;
655 }
656 assert_single_threaded();
657 inited = true;
658 """ % prefix
659 for tableName, table in sorted(schema.tables.iteritems()):
660 structName = "%s%s" % (prefix, tableName.lower())
661 print " %s_columns_init();" % structName
662 print "}"
663
664 print """
665 /* Return the schema version. The caller must not free the returned value. */
666 const char *
667 %sget_db_version(void)
668 {
669 return "%s";
670 }
671 """ % (prefix, schema.version)
672
673
674
675 def ovsdb_escape(string):
676 def escape(match):
677 c = match.group(0)
678 if c == '\0':
679 raise ovs.db.error.Error("strings may not contain null bytes")
680 elif c == '\\':
681 return '\\\\'
682 elif c == '\n':
683 return '\\n'
684 elif c == '\r':
685 return '\\r'
686 elif c == '\t':
687 return '\\t'
688 elif c == '\b':
689 return '\\b'
690 elif c == '\a':
691 return '\\a'
692 else:
693 return '\\x%02x' % ord(c)
694 return re.sub(r'["\\\000-\037]', escape, string)
695
696 def usage():
697 print """\
698 %(argv0)s: ovsdb schema compiler
699 usage: %(argv0)s [OPTIONS] COMMAND ARG...
700
701 The following commands are supported:
702 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
703 c-idl-header IDL print C header file for IDL
704 c-idl-source IDL print C source file for IDL implementation
705 nroff IDL print schema documentation in nroff format
706
707 The following options are also available:
708 -h, --help display this help message
709 -V, --version display version information\
710 """ % {'argv0': argv0}
711 sys.exit(0)
712
713 if __name__ == "__main__":
714 try:
715 try:
716 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
717 ['directory',
718 'help',
719 'version'])
720 except getopt.GetoptError, geo:
721 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
722 sys.exit(1)
723
724 for key, value in options:
725 if key in ['-h', '--help']:
726 usage()
727 elif key in ['-V', '--version']:
728 print "ovsdb-idlc (Open vSwitch) @VERSION@"
729 elif key in ['-C', '--directory']:
730 os.chdir(value)
731 else:
732 sys.exit(0)
733
734 optKeys = [key for key, value in options]
735
736 if not args:
737 sys.stderr.write("%s: missing command argument "
738 "(use --help for help)\n" % argv0)
739 sys.exit(1)
740
741 commands = {"annotate": (annotateSchema, 2),
742 "c-idl-header": (printCIDLHeader, 1),
743 "c-idl-source": (printCIDLSource, 1)}
744
745 if not args[0] in commands:
746 sys.stderr.write("%s: unknown command \"%s\" "
747 "(use --help for help)\n" % (argv0, args[0]))
748 sys.exit(1)
749
750 func, n_args = commands[args[0]]
751 if len(args) - 1 != n_args:
752 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
753 "provided\n"
754 % (argv0, args[0], n_args, len(args) - 1))
755 sys.exit(1)
756
757 func(*args[1:])
758 except ovs.db.error.Error, e:
759 sys.stderr.write("%s: %s\n" % (argv0, e))
760 sys.exit(1)
761
762 # Local variables:
763 # mode: python
764 # End: