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