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