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