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