ovsdb-server: Add commands for adding and removing remotes at runtime.
[sliver-openvswitch.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 <limits.h>
189 #include "ovsdb-data.h"
190 #include "ovsdb-error.h"
191 #include "util.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 "    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);"
245                 print "    }"
246             elif (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
247                 print
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())
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 "    ovs_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     ovs_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     ovs_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    ovs_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     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}
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     ovs_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 "    union ovsdb_atom key;"
521                 if type.value:
522                     print "    union ovsdb_atom value;"
523                 print
524                 print "    ovs_assert(inited);"
525                 print "    datum.n = 1;"
526                 print "    datum.keys = &key;"
527                 print "    " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
528                 if type.value:
529                     print "    datum.values = &value;"
530                     print "    "+ type.value.assign_c_value_casting_away_const("value.%s" % type.value.type.to_string(), valueVar)
531                 else:
532                     print "    datum.values = NULL;"
533                 txn_write_func = "ovsdb_idl_txn_write_clone"
534             elif type.is_optional_pointer():
535                 print "    union ovsdb_atom key;"
536                 print
537                 print "    ovs_assert(inited);"
538                 print "    if (%s) {" % keyVar
539                 print "        datum.n = 1;"
540                 print "        datum.keys = &key;"
541                 print "        " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
542                 print "    } else {"
543                 print "        datum.n = 0;"
544                 print "        datum.keys = NULL;"
545                 print "    }"
546                 print "    datum.values = NULL;"
547                 txn_write_func = "ovsdb_idl_txn_write_clone"
548             elif type.n_max == 1:
549                 print "    union ovsdb_atom key;"
550                 print
551                 print "    ovs_assert(inited);"
552                 print "    if (%s) {" % nVar
553                 print "        datum.n = 1;"
554                 print "        datum.keys = &key;"
555                 print "        " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), "*" + keyVar)
556                 print "    } else {"
557                 print "        datum.n = 0;"
558                 print "        datum.keys = NULL;"
559                 print "    }"
560                 print "    datum.values = NULL;"
561                 txn_write_func = "ovsdb_idl_txn_write_clone"
562             else:
563                 print "    size_t i;"
564                 print
565                 print "    ovs_assert(inited);"
566                 print "    datum.n = %s;" % nVar
567                 print "    datum.keys = %s ? xmalloc(%s * sizeof *datum.keys) : NULL;" % (nVar, nVar)
568                 if type.value:
569                     print "    datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
570                 else:
571                     print "    datum.values = NULL;"
572                 print "    for (i = 0; i < %s; i++) {" % nVar
573                 print "        " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
574                 if type.value:
575                     print "        " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
576                 print "    }"
577                 if type.value:
578                     valueType = type.value.toAtomicType()
579                 else:
580                     valueType = "OVSDB_TYPE_VOID"
581                 print "    ovsdb_datum_sort_unique(&datum, %s, %s);" % (
582                     type.key.toAtomicType(), valueType)
583                 txn_write_func = "ovsdb_idl_txn_write"
584             print "    %(f)s(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
585                 % {'f': txn_write_func,
586                    's': structName,
587                    'S': structName.upper(),
588                    'C': columnName.upper()}
589             print "}"
590
591         # Table columns.
592         print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
593             structName, structName.upper())
594         print """
595 static void\n%s_columns_init(void)
596 {
597     struct ovsdb_idl_column *c;\
598 """ % structName
599         for columnName, column in sorted(table.columns.iteritems()):
600             cs = "%s_col_%s" % (structName, columnName)
601             d = {'cs': cs, 'c': columnName, 's': structName}
602             if column.mutable:
603                 mutable = "true"
604             else:
605                 mutable = "false"
606             print
607             print "    /* Initialize %(cs)s. */" % d
608             print "    c = &%(cs)s;" % d
609             print "    c->name = \"%(c)s\";" % d
610             print column.type.cInitType("    ", "c->type")
611             print "    c->mutable = %s;" % mutable
612             print "    c->parse = %(s)s_parse_%(c)s;" % d
613             print "    c->unparse = %(s)s_unparse_%(c)s;" % d
614         print "}"
615
616     # Table classes.
617     print "\f"
618     print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
619     for tableName, table in sorted(schema.tables.iteritems()):
620         structName = "%s%s" % (prefix, tableName.lower())
621         if table.is_root:
622             is_root = "true"
623         else:
624             is_root = "false"
625         print "    {\"%s\", %s," % (tableName, is_root)
626         print "     %s_columns, ARRAY_SIZE(%s_columns)," % (
627             structName, structName)
628         print "     sizeof(struct %s), %s_init__}," % (structName, structName)
629     print "};"
630
631     # IDL class.
632     print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
633     print "    \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
634         schema.name, prefix, prefix)
635     print "};"
636
637     # global init function
638     print """
639 void
640 %sinit(void)
641 {
642     if (inited) {
643         return;
644     }
645     inited = true;
646 """ % prefix
647     for tableName, table in sorted(schema.tables.iteritems()):
648         structName = "%s%s" % (prefix, tableName.lower())
649         print "    %s_columns_init();" % structName
650     print "}"
651
652
653 def ovsdb_escape(string):
654     def escape(match):
655         c = match.group(0)
656         if c == '\0':
657             raise ovs.db.error.Error("strings may not contain null bytes")
658         elif c == '\\':
659             return '\\\\'
660         elif c == '\n':
661             return '\\n'
662         elif c == '\r':
663             return '\\r'
664         elif c == '\t':
665             return '\\t'
666         elif c == '\b':
667             return '\\b'
668         elif c == '\a':
669             return '\\a'
670         else:
671             return '\\x%02x' % ord(c)
672     return re.sub(r'["\\\000-\037]', escape, string)
673
674 def usage():
675     print """\
676 %(argv0)s: ovsdb schema compiler
677 usage: %(argv0)s [OPTIONS] COMMAND ARG...
678
679 The following commands are supported:
680   annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
681   c-idl-header IDL            print C header file for IDL
682   c-idl-source IDL            print C source file for IDL implementation
683   nroff IDL                   print schema documentation in nroff format
684
685 The following options are also available:
686   -h, --help                  display this help message
687   -V, --version               display version information\
688 """ % {'argv0': argv0}
689     sys.exit(0)
690
691 if __name__ == "__main__":
692     try:
693         try:
694             options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
695                                               ['directory',
696                                                'help',
697                                                'version'])
698         except getopt.GetoptError, geo:
699             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
700             sys.exit(1)
701
702         for key, value in options:
703             if key in ['-h', '--help']:
704                 usage()
705             elif key in ['-V', '--version']:
706                 print "ovsdb-idlc (Open vSwitch) @VERSION@"
707             elif key in ['-C', '--directory']:
708                 os.chdir(value)
709             else:
710                 sys.exit(0)
711
712         optKeys = [key for key, value in options]
713
714         if not args:
715             sys.stderr.write("%s: missing command argument "
716                              "(use --help for help)\n" % argv0)
717             sys.exit(1)
718
719         commands = {"annotate": (annotateSchema, 2),
720                     "c-idl-header": (printCIDLHeader, 1),
721                     "c-idl-source": (printCIDLSource, 1)}
722
723         if not args[0] in commands:
724             sys.stderr.write("%s: unknown command \"%s\" "
725                              "(use --help for help)\n" % (argv0, args[0]))
726             sys.exit(1)
727
728         func, n_args = commands[args[0]]
729         if len(args) - 1 != n_args:
730             sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
731                              "provided\n"
732                              % (argv0, args[0], n_args, len(args) - 1))
733             sys.exit(1)
734
735         func(*args[1:])
736     except ovs.db.error.Error, e:
737         sys.stderr.write("%s: %s\n" % (argv0, e))
738         sys.exit(1)
739
740 # Local variables:
741 # mode: python
742 # End: