]> git.proxmox.com Git - mirror_ovs.git/blob - ovsdb/ovsdb-idlc.in
ovsdb: Enforce immutability of immutable columns.
[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
22 def constify(cType, const):
23 if (const and cType.endswith('*') and not cType.endswith('**')):
24 return 'const %s' % cType
25 else:
26 return cType
27
28 def cMembers(prefix, columnName, column, const):
29 type = column.type
30
31 if type.is_smap():
32 return [{'name': columnName,
33 'type': 'struct smap ',
34 'comment': ''}]
35
36 if type.n_min == 1 and type.n_max == 1:
37 singleton = True
38 pointer = ''
39 else:
40 singleton = False
41 if type.is_optional_pointer():
42 pointer = ''
43 else:
44 pointer = '*'
45
46 if type.value:
47 key = {'name': "key_%s" % columnName,
48 'type': constify(type.key.toCType(prefix) + pointer, const),
49 'comment': ''}
50 value = {'name': "value_%s" % columnName,
51 'type': constify(type.value.toCType(prefix) + pointer, const),
52 'comment': ''}
53 members = [key, value]
54 else:
55 m = {'name': columnName,
56 'type': constify(type.key.toCType(prefix) + pointer, const),
57 'comment': type.cDeclComment()}
58 members = [m]
59
60 if not singleton and not type.is_optional_pointer():
61 members.append({'name': 'n_%s' % columnName,
62 'type': 'size_t ',
63 'comment': ''})
64 return members
65
66 def printCIDLHeader(schemaFile):
67 schema = parseSchema(schemaFile)
68 prefix = schema.idlPrefix
69 print '''\
70 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
71
72 #ifndef %(prefix)sIDL_HEADER
73 #define %(prefix)sIDL_HEADER 1
74
75 #include <stdbool.h>
76 #include <stddef.h>
77 #include <stdint.h>
78 #include "ovsdb-data.h"
79 #include "ovsdb-idl-provider.h"
80 #include "smap.h"
81 #include "uuid.h"''' % {'prefix': prefix.upper()}
82
83 for tableName, table in sorted(schema.tables.iteritems()):
84 structName = "%s%s" % (prefix, tableName.lower())
85
86 print "\f"
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
94 print "};"
95
96 # Column indexes.
97 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
98 for columnName in sorted(table.columns)]
99 + ["%s_N_COLUMNS" % structName.upper()])
100
101 print
102 for columnName in table.columns:
103 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
104 's': structName,
105 'S': structName.upper(),
106 'c': columnName,
107 'C': columnName.upper()}
108
109 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
110
111 print '''
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); \\
116 (ROW); \\
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; \\
121 (ROW) = (NEXT))
122
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()}
127
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}
130
131 print """
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'
138 else:
139 valueParam = ''
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}
142
143 print
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 *']
148 else:
149 args = ['%(type)s%(name)s' % member for member
150 in cMembers(prefix, columnName, column, True)]
151 print '%s);' % ', '.join(args)
152
153 print
154
155 # Table indexes.
156 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
157 print
158 for tableName in schema.tables:
159 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
160 'p': prefix,
161 'P': prefix.upper(),
162 't': tableName.lower(),
163 'T': tableName.upper()}
164 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
165
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()}
169
170 def printEnum(members):
171 if len(members) == 0:
172 return
173
174 print "\nenum {";
175 for member in members[:-1]:
176 print " %s," % member
177 print " %s" % members[-1]
178 print "};"
179
180 def printCIDLSource(schemaFile):
181 schema = parseSchema(schemaFile)
182 prefix = schema.idlPrefix
183 print '''\
184 /* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
185
186 #include <config.h>
187 #include %s
188 #include <assert.h>
189 #include <limits.h>
190 #include "ovsdb-data.h"
191 #include "ovsdb-error.h"
192
193 #ifdef __CHECKER__
194 /* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
195 enum { sizeof_bool = 1 };
196 #else
197 enum { sizeof_bool = sizeof(bool) };
198 #endif
199
200 static bool inited;
201 ''' % schema.idlHeader
202
203 # Cast functions.
204 for tableName, table in sorted(schema.tables.iteritems()):
205 structName = "%s%s" % (prefix, tableName.lower())
206 print '''
207 static struct %(s)s *
208 %(s)s_cast(const struct ovsdb_idl_row *row)
209 {
210 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
211 }\
212 ''' % {'s': structName}
213
214
215 for tableName, table in sorted(schema.tables.iteritems()):
216 structName = "%s%s" % (prefix, tableName.lower())
217 print "\f"
218 print "/* %s table. */" % (tableName)
219
220 # Parse functions.
221 for columnName, column in sorted(table.columns.iteritems()):
222 print '''
223 static void
224 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
225 {
226 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
227 'c': columnName}
228 type = column.type
229 if type.value:
230 keyVar = "row->key_%s" % columnName
231 valueVar = "row->value_%s" % columnName
232 else:
233 keyVar = "row->%s" % columnName
234 valueVar = None
235
236 if type.is_smap():
237 print " size_t i;"
238 print
239 print " 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);"
245 print " }"
246 elif (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
247 print
248 print " 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())
252 else:
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())
254
255 if valueVar:
256 if type.value.ref_table:
257 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
258 else:
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())
260 print " } else {"
261 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
262 if valueVar:
263 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
264 print " }"
265 else:
266 if type.n_max != sys.maxint:
267 print " size_t n = MIN(%d, datum->n);" % type.n_max
268 nMax = "n"
269 else:
270 nMax = "datum->n"
271 print " size_t i;"
272 print
273 print " assert(inited);"
274 print " %s = NULL;" % keyVar
275 if valueVar:
276 print " %s = NULL;" % valueVar
277 print " row->n_%s = 0;" % columnName
278 print " for (i = 0; i < %s; i++) {" % nMax
279 refs = []
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())
282 keySrc = "keyRow"
283 refs.append('keyRow')
284 else:
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')
290 elif valueVar:
291 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
292 if refs:
293 print " if (%s) {" % ' && '.join(refs)
294 indent = " "
295 else:
296 indent = " "
297 print "%sif (!row->n_%s) {" % (indent, columnName)
298
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"
304 else:
305 sizeof = "sizeof *%s" % keyVar
306 print "%s %s = xmalloc(%s * %s);" % (indent, keyVar, nMax,
307 sizeof)
308 if valueVar:
309 # Special case for boolean types (see above).
310 if type.value.type == ovs.db.types.BooleanType:
311 sizeof = " * sizeof_bool"
312 else:
313 sizeof = "sizeof *%s" % valueVar
314 print "%s %s = xmalloc(%s * %s);" % (indent, valueVar,
315 nMax, sizeof)
316 print "%s}" % indent
317 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
318 if valueVar:
319 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
320 print "%srow->n_%s++;" % (indent, columnName)
321 if refs:
322 print " }"
323 print " }"
324 print "}"
325
326 # Unparse functions.
327 for columnName, column in sorted(table.columns.iteritems()):
328 type = column.type
329 if type.is_smap() or (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
330 print '''
331 static void
332 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
333 {
334 struct %(s)s *row = %(s)s_cast(row_);
335
336 assert(inited);''' % {'s': structName, 'c': columnName}
337
338 if type.is_smap():
339 print " smap_destroy(&row->%s);" % columnName
340 else:
341 if type.value:
342 keyVar = "row->key_%s" % columnName
343 valueVar = "row->value_%s" % columnName
344 else:
345 keyVar = "row->%s" % columnName
346 valueVar = None
347 print " free(%s);" % keyVar
348 if valueVar:
349 print " free(%s);" % valueVar
350 print '}'
351 else:
352 print '''
353 static void
354 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
355 {
356 /* Nothing to do. */
357 }''' % {'s': structName, 'c': columnName}
358
359 # Generic Row Initialization function.
360 print """
361 static void
362 %(s)s_init__(struct ovsdb_idl_row *row)
363 {
364 %(s)s_init(%(s)s_cast(row));
365 }""" % {'s': structName}
366
367 # Row Initialization function.
368 print """
369 void
370 %(s)s_init(struct %(s)s *row)
371 {
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
376 print "}"
377
378 # First, next functions.
379 print '''
380 const struct %(s)s *
381 %(s)s_first(const struct ovsdb_idl *idl)
382 {
383 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
384 }
385
386 const struct %(s)s *
387 %(s)s_next(const struct %(s)s *row)
388 {
389 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
390 }''' % {'s': structName,
391 'p': prefix,
392 'P': prefix.upper(),
393 'T': tableName.upper()}
394
395 print '''
396 void
397 %(s)s_delete(const struct %(s)s *row)
398 {
399 ovsdb_idl_txn_delete(&row->header_);
400 }
401
402 struct %(s)s *
403 %(s)s_insert(struct ovsdb_idl_txn *txn)
404 {
405 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
406 }
407 ''' % {'s': structName,
408 'p': prefix,
409 'P': prefix.upper(),
410 'T': tableName.upper()}
411
412 # Verify functions.
413 for columnName, column in sorted(table.columns.iteritems()):
414 print '''
415 void
416 %(s)s_verify_%(c)s(const struct %(s)s *row)
417 {
418 assert(inited);
419 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
420 }''' % {'s': structName,
421 'S': structName.upper(),
422 'c': columnName,
423 'C': columnName.upper()}
424
425 # Get functions.
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 assert(value_type == %s);' % column.type.value.toAtomicType()
430 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
431 else:
432 valueParam = ''
433 valueType = ''
434 valueComment = ''
435 print """
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'.
440 *
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.)
444 *
445 * The caller must not modify or free the returned value.
446 *
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)
454 {
455 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}
460
461 # Set functions.
462 for columnName, column in sorted(table.columns.iteritems()):
463 type = column.type
464
465 if type.is_smap():
466 print """
467 void
468 %(s)s_set_%(c)s(const struct %(s)s *row, const struct smap *smap)
469 {
470 struct ovsdb_datum datum;
471
472 assert(inited);
473 if (smap) {
474 struct smap_node *node;
475 size_t i;
476
477 datum.n = smap_count(smap);
478 datum.keys = xmalloc(datum.n * sizeof *datum.keys);
479 datum.values = xmalloc(datum.n * sizeof *datum.values);
480
481 i = 0;
482 SMAP_FOR_EACH (node, smap) {
483 datum.keys[i].string = xstrdup(node->key);
484 datum.values[i].string = xstrdup(node->value);
485 i++;
486 }
487 ovsdb_datum_sort_unique(&datum, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
488 } else {
489 ovsdb_datum_init_empty(&datum);
490 }
491 ovsdb_idl_txn_write(&row->header_,
492 &%(s)s_columns[%(S)s_COL_%(C)s],
493 &datum);
494 }
495 """ % {'s': structName,
496 'S': structName.upper(),
497 'c': columnName,
498 'C': columnName.upper()}
499 continue
500
501
502 print '\nvoid'
503 members = cMembers(prefix, columnName, column, True)
504 keyVar = members[0]['name']
505 nVar = None
506 valueVar = None
507 if type.value:
508 valueVar = members[1]['name']
509 if len(members) > 2:
510 nVar = members[2]['name']
511 else:
512 if len(members) > 1:
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])}
517 print "{"
518 print " struct ovsdb_datum datum;"
519 if type.n_min == 1 and type.n_max == 1:
520 print
521 print " 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)
525 if type.value:
526 print " datum.values = xmalloc(sizeof *datum.values);"
527 print " "+ type.value.copyCValue("datum.values[0].%s" % type.value.type.to_string(), valueVar)
528 else:
529 print " datum.values = NULL;"
530 elif type.is_optional_pointer():
531 print
532 print " 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)
537 print " } else {"
538 print " datum.n = 0;"
539 print " datum.keys = NULL;"
540 print " }"
541 print " datum.values = NULL;"
542 else:
543 print " size_t i;"
544 print
545 print " assert(inited);"
546 print " datum.n = %s;" % nVar
547 print " datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
548 if type.value:
549 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
550 else:
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)
554 if type.value:
555 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
556 print " }"
557 if type.value:
558 valueType = type.value.toAtomicType()
559 else:
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);" \
564 % {'s': structName,
565 'S': structName.upper(),
566 'C': columnName.upper()}
567 print "}"
568
569 # Table columns.
570 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
571 structName, structName.upper())
572 print """
573 static void\n%s_columns_init(void)
574 {
575 struct ovsdb_idl_column *c;\
576 """ % structName
577 for columnName, column in sorted(table.columns.iteritems()):
578 cs = "%s_col_%s" % (structName, columnName)
579 d = {'cs': cs, 'c': columnName, 's': structName}
580 if column.mutable:
581 mutable = "true"
582 else:
583 mutable = "false"
584 print
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
592 print "}"
593
594 # Table classes.
595 print "\f"
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())
599 if table.is_root:
600 is_root = "true"
601 else:
602 is_root = "false"
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)
607 print "};"
608
609 # IDL class.
610 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
611 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
612 schema.name, prefix, prefix)
613 print "};"
614
615 # global init function
616 print """
617 void
618 %sinit(void)
619 {
620 if (inited) {
621 return;
622 }
623 inited = true;
624 """ % prefix
625 for tableName, table in sorted(schema.tables.iteritems()):
626 structName = "%s%s" % (prefix, tableName.lower())
627 print " %s_columns_init();" % structName
628 print "}"
629
630
631 def ovsdb_escape(string):
632 def escape(match):
633 c = match.group(0)
634 if c == '\0':
635 raise ovs.db.error.Error("strings may not contain null bytes")
636 elif c == '\\':
637 return '\\\\'
638 elif c == '\n':
639 return '\\n'
640 elif c == '\r':
641 return '\\r'
642 elif c == '\t':
643 return '\\t'
644 elif c == '\b':
645 return '\\b'
646 elif c == '\a':
647 return '\\a'
648 else:
649 return '\\x%02x' % ord(c)
650 return re.sub(r'["\\\000-\037]', escape, string)
651
652 def usage():
653 print """\
654 %(argv0)s: ovsdb schema compiler
655 usage: %(argv0)s [OPTIONS] COMMAND ARG...
656
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
662
663 The following options are also available:
664 -h, --help display this help message
665 -V, --version display version information\
666 """ % {'argv0': argv0}
667 sys.exit(0)
668
669 if __name__ == "__main__":
670 try:
671 try:
672 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
673 ['directory',
674 'help',
675 'version'])
676 except getopt.GetoptError, geo:
677 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
678 sys.exit(1)
679
680 for key, value in options:
681 if key in ['-h', '--help']:
682 usage()
683 elif key in ['-V', '--version']:
684 print "ovsdb-idlc (Open vSwitch) @VERSION@"
685 elif key in ['-C', '--directory']:
686 os.chdir(value)
687 else:
688 sys.exit(0)
689
690 optKeys = [key for key, value in options]
691
692 if not args:
693 sys.stderr.write("%s: missing command argument "
694 "(use --help for help)\n" % argv0)
695 sys.exit(1)
696
697 commands = {"annotate": (annotateSchema, 2),
698 "c-idl-header": (printCIDLHeader, 1),
699 "c-idl-source": (printCIDLSource, 1)}
700
701 if not args[0] in commands:
702 sys.stderr.write("%s: unknown command \"%s\" "
703 "(use --help for help)\n" % (argv0, args[0]))
704 sys.exit(1)
705
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 "
709 "provided\n"
710 % (argv0, args[0], n_args, len(args) - 1))
711 sys.exit(1)
712
713 func(*args[1:])
714 except ovs.db.error.Error, e:
715 sys.stderr.write("%s: %s\n" % (argv0, e))
716 sys.exit(1)
717
718 # Local variables:
719 # mode: python
720 # End: