]> git.proxmox.com Git - ovs.git/blame - ovsdb/ovsdb-idlc.in
ovn-controller: Use new ovsdb-idl helpers to make logic more readable.
[ovs.git] / ovsdb / ovsdb-idlc.in
CommitLineData
d879a707
BP
1#! @PYTHON@
2
3import getopt
00732bf5 4import os
d879a707 5import re
d879a707
BP
6import sys
7
99155935
BP
8import ovs.json
9import ovs.db.error
10import ovs.db.schema
d879a707 11
89365653 12argv0 = sys.argv[0]
45a7de56 13
d879a707 14def parseSchema(filename):
99155935 15 return ovs.db.schema.IdlSchema.from_json(ovs.json.from_file(filename))
00732bf5
BP
16
17def annotateSchema(schemaFile, annotationFile):
99155935 18 schemaJson = ovs.json.from_file(schemaFile)
00732bf5 19 execfile(annotationFile, globals(), {"s": schemaJson})
99155935 20 ovs.json.to_stream(schemaJson, sys.stdout)
292aefc4 21 sys.stdout.write('\n')
d879a707 22
02630ff2 23def constify(cType, const):
47058293
RB
24 if (const
25 and cType.endswith('*') and
26 (cType == 'char **' or not cType.endswith('**'))):
02630ff2
BP
27 return 'const %s' % cType
28 else:
29 return cType
30
7cc398cb
JP
31def cMembers(prefix, tableName, columnName, column, const):
32 comment = ""
475281c0 33 type = column.type
a699f614
EJ
34
35 if type.is_smap():
7cc398cb
JP
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)
a699f614 49
99155935 50 if type.n_min == 1 and type.n_max == 1:
475281c0
BP
51 singleton = True
52 pointer = ''
53 else:
54 singleton = False
99155935 55 if type.is_optional_pointer():
475281c0
BP
56 pointer = ''
57 else:
58 pointer = '*'
59
7cc398cb 60
475281c0 61 if type.value:
7cc398cb
JP
62 keyName = "key_%s" % columnName
63 valueName = "value_%s" % columnName
64
65 key = {'name': keyName,
bd76d25d 66 'type': constify(type.key.toCType(prefix) + pointer, const),
475281c0 67 'comment': ''}
7cc398cb 68 value = {'name': valueName,
bd76d25d 69 'type': constify(type.value.toCType(prefix) + pointer, const),
475281c0 70 'comment': ''}
7cc398cb
JP
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)
475281c0
BP
78 members = [key, value]
79 else:
80 m = {'name': columnName,
bd76d25d
BP
81 'type': constify(type.key.toCType(prefix) + pointer, const),
82 'comment': type.cDeclComment()}
7cc398cb
JP
83
84 if singleton:
85 comment += " * '%s'" % columnName
86 else:
87 comment += " * the '%s' set" % columnName
475281c0
BP
88 members = [m]
89
99155935 90 if not singleton and not type.is_optional_pointer():
7cc398cb
JP
91 sizeName = "n_%s" % columnName
92
93 comment += " with '%s' entries" % sizeName
94 members.append({'name': sizeName,
475281c0
BP
95 'type': 'size_t ',
96 'comment': ''})
7cc398cb
JP
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)
475281c0 119
00732bf5
BP
120def printCIDLHeader(schemaFile):
121 schema = parseSchema(schemaFile)
c3bb4bd7 122 prefix = schema.idlPrefix
d879a707
BP
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>
a6ec9089 132#include "ovsdb-data.h"
c3bb4bd7 133#include "ovsdb-idl-provider.h"
a699f614 134#include "smap.h"
d879a707 135#include "uuid.h"''' % {'prefix': prefix.upper()}
979821c0 136
bd76d25d 137 for tableName, table in sorted(schema.tables.iteritems()):
c3bb4bd7 138 structName = "%s%s" % (prefix, tableName.lower())
979821c0
BP
139
140 print "\f"
141 print "/* %s table. */" % tableName
c3bb4bd7
BP
142 print "struct %s {" % structName
143 print "\tstruct ovsdb_idl_row header_;"
bd76d25d 144 for columnName, column in sorted(table.columns.iteritems()):
d879a707 145 print "\n\t/* %s column. */" % columnName
7cc398cb
JP
146 comment, members = cMembers(prefix, tableName,
147 columnName, column, False)
148 for member in members:
475281c0 149 print "\t%(type)s%(name)s;%(comment)s" % member
979821c0 150 print "};"
c3bb4bd7 151
979821c0 152 # Column indexes.
32d37ce8 153 printEnum("%s_column_id" % structName.lower(), ["%s_COL_%s" % (structName.upper(), columnName.upper())
bd76d25d 154 for columnName in sorted(table.columns)]
979821c0
BP
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 '''
8c6cf7b8 168const struct %(s)s *%(s)s_get_for_uuid(const struct ovsdb_idl *, const struct uuid *);
c3bb4bd7
BP
169const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
170const struct %(s)s *%(s)s_next(const struct %(s)s *);
58bc1a52
BP
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))
475281c0 179
932104f4
SA
180unsigned int %(s)s_get_seqno(const struct ovsdb_idl *);
181unsigned int %(s)s_row_get_seqno(const struct %(s)s *row, enum ovsdb_idl_change change);
182const struct %(s)s *%(s)s_track_get_first(const struct ovsdb_idl *);
183const 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
9a33cd70
BP
189/* Returns true if 'row' was inserted since the last change tracking reset. */
190static 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. */
196static 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
a699f614 201void %(s)s_init(struct %(s)s *);
475281c0
BP
202void %(s)s_delete(const struct %(s)s *);
203struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
32d37ce8 204bool %(s)s_is_updated(const struct %(s)s *, enum %(s)s_column_id);
475281c0
BP
205''' % {'s': structName, 'S': structName.upper()}
206
bd76d25d 207 for columnName, column in sorted(table.columns.iteritems()):
475281c0
BP
208 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
209
e8cc1bb1 210 print
a6ec9089
BP
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
475281c0 219 print
bd76d25d 220 for columnName, column in sorted(table.columns.iteritems()):
475281c0 221 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
a699f614
EJ
222 if column.type.is_smap():
223 args = ['const struct smap *']
224 else:
7cc398cb
JP
225 comment, members = cMembers(prefix, tableName, columnName,
226 column, True)
227 args = ['%(type)s%(name)s' % member for member in members]
475281c0
BP
228 print '%s);' % ', '.join(args)
229
f67f1354 230 print
010fe7ae
EA
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
f67f1354 238
979821c0 239 # Table indexes.
32d37ce8 240 printEnum("%stable_id" % prefix.lower(), ["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
979821c0
BP
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
c3bb4bd7 250 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
bd76d25d 251 print "\nvoid %sinit(void);" % prefix
87412f02
JP
252
253 print "\nconst char * %sget_db_version(void);" % prefix
c3bb4bd7
BP
254 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
255
32d37ce8 256def printEnum(type, members):
c3bb4bd7
BP
257 if len(members) == 0:
258 return
259
32d37ce8 260 print "\nenum %s {" % type
c3bb4bd7
BP
261 for member in members[:-1]:
262 print " %s," % member
263 print " %s" % members[-1]
264 print "};"
265
00732bf5
BP
266def printCIDLSource(schemaFile):
267 schema = parseSchema(schemaFile)
c3bb4bd7
BP
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>
558103f0 275#include "ovs-thread.h"
bd76d25d
BP
276#include "ovsdb-data.h"
277#include "ovsdb-error.h"
cb22974d 278#include "util.h"
bd76d25d 279
1bf2c909
EJ
280#ifdef __CHECKER__
281/* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
282enum { sizeof_bool = 1 };
283#else
284enum { sizeof_bool = sizeof(bool) };
285#endif
286
bd76d25d 287static bool inited;
89521e3f 288''' % schema.idlHeader
c3bb4bd7 289
66095e15 290 # Cast functions.
bd76d25d 291 for tableName, table in sorted(schema.tables.iteritems()):
66095e15
BP
292 structName = "%s%s" % (prefix, tableName.lower())
293 print '''
294static struct %(s)s *
979821c0 295%(s)s_cast(const struct ovsdb_idl_row *row)
66095e15
BP
296{
297 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
298}\
299''' % {'s': structName}
300
301
bd76d25d 302 for tableName, table in sorted(schema.tables.iteritems()):
c3bb4bd7
BP
303 structName = "%s%s" % (prefix, tableName.lower())
304 print "\f"
2e57b537 305 print "/* %s table. */" % (tableName)
c3bb4bd7 306
979821c0 307 # Parse functions.
bd76d25d 308 for columnName, column in sorted(table.columns.iteritems()):
979821c0 309 print '''
c3bb4bd7 310static void
979821c0 311%(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
c3bb4bd7 312{
979821c0
BP
313 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
314 'c': columnName}
c3bb4bd7 315 type = column.type
c3bb4bd7
BP
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
a699f614
EJ
323 if type.is_smap():
324 print " size_t i;"
325 print
cb22974d 326 print " ovs_assert(inited);"
a699f614
EJ
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():
979821c0 334 print
cb22974d 335 print " ovs_assert(inited);"
c3bb4bd7 336 print " if (datum->n >= 1) {"
99155935
BP
337 if not type.key.ref_table:
338 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
c3bb4bd7 339 else:
7cba02e4 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())
c3bb4bd7
BP
341
342 if valueVar:
99155935
BP
343 if type.value.ref_table:
344 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
c3bb4bd7 345 else:
7cba02e4 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())
979821c0 347 print " } else {"
99155935 348 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
979821c0 349 if valueVar:
99155935 350 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
c3bb4bd7
BP
351 print " }"
352 else:
99155935
BP
353 if type.n_max != sys.maxint:
354 print " size_t n = MIN(%d, datum->n);" % type.n_max
979821c0 355 nMax = "n"
c3bb4bd7
BP
356 else:
357 nMax = "datum->n"
979821c0
BP
358 print " size_t i;"
359 print
cb22974d 360 print " ovs_assert(inited);"
979821c0
BP
361 print " %s = NULL;" % keyVar
362 if valueVar:
363 print " %s = NULL;" % valueVar
364 print " row->n_%s = 0;" % columnName
c3bb4bd7
BP
365 print " for (i = 0; i < %s; i++) {" % nMax
366 refs = []
99155935 367 if type.key.ref_table:
7cba02e4 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())
c3bb4bd7
BP
369 keySrc = "keyRow"
370 refs.append('keyRow')
371 else:
99155935
BP
372 keySrc = "datum->keys[i].%s" % type.key.type.to_string()
373 if type.value and type.value.ref_table:
7cba02e4 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())
c3bb4bd7
BP
375 valueSrc = "valueRow"
376 refs.append('valueRow')
377 elif valueVar:
99155935 378 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
c3bb4bd7
BP
379 if refs:
380 print " if (%s) {" % ' && '.join(refs)
381 indent = " "
382 else:
383 indent = " "
384 print "%sif (!row->n_%s) {" % (indent, columnName)
1bf2c909
EJ
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)
c3bb4bd7 395 if valueVar:
1bf2c909
EJ
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)
c3bb4bd7
BP
403 print "%s}" % indent
404 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
405 if valueVar:
66095e15 406 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
c3bb4bd7
BP
407 print "%srow->n_%s++;" % (indent, columnName)
408 if refs:
409 print " }"
410 print " }"
979821c0 411 print "}"
c3bb4bd7 412
979821c0 413 # Unparse functions.
bd76d25d 414 for columnName, column in sorted(table.columns.iteritems()):
c3bb4bd7 415 type = column.type
a699f614 416 if type.is_smap() or (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
979821c0 417 print '''
c3bb4bd7 418static void
979821c0 419%(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
c3bb4bd7 420{
979821c0 421 struct %(s)s *row = %(s)s_cast(row_);
bd76d25d 422
cb22974d 423 ovs_assert(inited);''' % {'s': structName, 'c': columnName}
a699f614
EJ
424
425 if type.is_smap():
426 print " smap_destroy(&row->%s);" % columnName
c3bb4bd7 427 else:
a699f614
EJ
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
979821c0
BP
437 print '}'
438 else:
439 print '''
c3bb4bd7 440static void
c69ee87c 441%(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
979821c0
BP
442{
443 /* Nothing to do. */
444}''' % {'s': structName, 'c': columnName}
c5c7c7c5 445
a699f614
EJ
446 # Generic Row Initialization function.
447 print """
448static 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 """
d797877d 456/* Clears the contents of 'row' in table "%(t)s". */
a699f614
EJ
457void
458%(s)s_init(struct %(s)s *row)
459{
d797877d 460 memset(row, 0, sizeof *row); """ % {'s': structName, 't': tableName}
a699f614
EJ
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
c3bb4bd7
BP
466 # First, next functions.
467 print '''
d797877d
JP
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. */
8c6cf7b8
BP
470const 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
d797877d
JP
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. */
66095e15
BP
482const struct %(s)s *
483%(s)s_first(const struct ovsdb_idl *idl)
c3bb4bd7 484{
66095e15 485 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
c3bb4bd7
BP
486}
487
d797877d
JP
488/* Returns a row following 'row' within its table, or a null pointer if 'row'
489 * is the last row in its table. */
66095e15
BP
490const struct %(s)s *
491%(s)s_next(const struct %(s)s *row)
c3bb4bd7 492{
66095e15 493 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
932104f4
SA
494}
495
496unsigned 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
501unsigned 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
506const 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
512const 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_));
475281c0
BP
516}''' % {'s': structName,
517 'p': prefix,
518 'P': prefix.upper(),
d797877d 519 't': tableName,
475281c0
BP
520 'T': tableName.upper()}
521
522 print '''
932104f4 523
d797877d
JP
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(). */
475281c0 528void
9e336f49 529%(s)s_delete(const struct %(s)s *row)
475281c0 530{
475281c0
BP
531 ovsdb_idl_txn_delete(&row->header_);
532}
533
d797877d
JP
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. */
475281c0
BP
541struct %(s)s *
542%(s)s_insert(struct ovsdb_idl_txn *txn)
543{
ce5a3e38 544 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
32d37ce8
SA
545}
546
547bool
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]);
d797877d
JP
551}''' % {'s': structName,
552 'p': prefix,
553 'P': prefix.upper(),
554 't': tableName,
555 'T': tableName.upper()}
475281c0
BP
556
557 # Verify functions.
bd76d25d 558 for columnName, column in sorted(table.columns.iteritems()):
475281c0 559 print '''
d797877d
JP
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(). */
475281c0
BP
585void
586%(s)s_verify_%(c)s(const struct %(s)s *row)
587{
cb22974d 588 ovs_assert(inited);
475281c0
BP
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
a6ec9089
BP
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'
cb22974d 599 valueType = '\n ovs_assert(value_type == %s);' % column.type.value.toAtomicType()
a6ec9089
BP
600 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
601 else:
602 valueParam = ''
603 valueType = ''
604 valueComment = ''
605 print """
d797877d
JP
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'.
a6ec9089
BP
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
d797877d
JP
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. */
a6ec9089
BP
625const 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{
cb22974d 629 ovs_assert(key_type == %(kt)s);%(vt)s
a6ec9089 630 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
d797877d 631}""" % {'t': tableName, 's': structName, 'c': columnName,
a6ec9089
BP
632 'kt': column.type.key.toAtomicType(),
633 'v': valueParam, 'vt': valueType, 'vc': valueComment}
634
475281c0 635 # Set functions.
bd76d25d 636 for columnName, column in sorted(table.columns.iteritems()):
475281c0 637 type = column.type
a699f614 638
7cc398cb
JP
639 comment, members = cMembers(prefix, tableName, columnName,
640 column, True)
641
a699f614 642 if type.is_smap():
7cc398cb
JP
643 print comment
644 print """void
4946b41d 645%(s)s_set_%(c)s(const struct %(s)s *row, const struct smap *%(c)s)
a699f614
EJ
646{
647 struct ovsdb_datum datum;
648
cb22974d 649 ovs_assert(inited);
4946b41d 650 if (%(c)s) {
a699f614
EJ
651 struct smap_node *node;
652 size_t i;
653
4946b41d 654 datum.n = smap_count(%(c)s);
a699f614
EJ
655 datum.keys = xmalloc(datum.n * sizeof *datum.keys);
656 datum.values = xmalloc(datum.n * sizeof *datum.values);
657
658 i = 0;
4946b41d 659 SMAP_FOR_EACH (node, %(c)s) {
a699f614
EJ
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}
7cc398cb
JP
672""" % {'t': tableName,
673 's': structName,
a699f614
EJ
674 'S': structName.upper(),
675 'c': columnName,
676 'C': columnName.upper()}
677 continue
678
475281c0
BP
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']
7cc398cb
JP
689
690 print comment
691 print 'void'
979821c0 692 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
475281c0
BP
693 {'s': structName, 'c': columnName,
694 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
695 print "{"
475281c0 696 print " struct ovsdb_datum datum;"
99155935 697 if type.n_min == 1 and type.n_max == 1:
fe19569a
BP
698 print " union ovsdb_atom key;"
699 if type.value:
700 print " union ovsdb_atom value;"
475281c0 701 print
cb22974d 702 print " ovs_assert(inited);"
475281c0 703 print " datum.n = 1;"
fe19569a
BP
704 print " datum.keys = &key;"
705 print " " + type.key.assign_c_value_casting_away_const("key.%s" % type.key.type.to_string(), keyVar)
475281c0 706 if type.value:
fe19569a
BP
707 print " datum.values = &value;"
708 print " "+ type.value.assign_c_value_casting_away_const("value.%s" % type.value.type.to_string(), valueVar)
475281c0
BP
709 else:
710 print " datum.values = NULL;"
fe19569a 711 txn_write_func = "ovsdb_idl_txn_write_clone"
99155935 712 elif type.is_optional_pointer():
fe19569a 713 print " union ovsdb_atom key;"
475281c0 714 print
cb22974d 715 print " ovs_assert(inited);"
475281c0
BP
716 print " if (%s) {" % keyVar
717 print " datum.n = 1;"
fe19569a
BP
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)
475281c0
BP
734 print " } else {"
735 print " datum.n = 0;"
736 print " datum.keys = NULL;"
737 print " }"
738 print " datum.values = NULL;"
fe19569a 739 txn_write_func = "ovsdb_idl_txn_write_clone"
475281c0
BP
740 else:
741 print " size_t i;"
742 print
cb22974d 743 print " ovs_assert(inited);"
475281c0 744 print " datum.n = %s;" % nVar
fe19569a 745 print " datum.keys = %s ? xmalloc(%s * sizeof *datum.keys) : NULL;" % (nVar, nVar)
475281c0
BP
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
99155935 751 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
475281c0 752 if type.value:
99155935 753 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
475281c0 754 print " }"
a1ec42a3
BP
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)
fe19569a
BP
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,
475281c0
BP
765 'S': structName.upper(),
766 'C': columnName.upper()}
767 print "}"
010fe7ae
EA
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 */
777void
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 */
806void
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
c3bb4bd7
BP
830
831 # Table columns.
bd76d25d 832 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
c3bb4bd7 833 structName, structName.upper())
bd76d25d
BP
834 print """
835static 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}
341c4e59
BP
842 if column.mutable:
843 mutable = "true"
844 else:
845 mutable = "false"
bd76d25d
BP
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")
341c4e59 851 print " c->mutable = %s;" % mutable
bd76d25d
BP
852 print " c->parse = %(s)s_parse_%(c)s;" % d
853 print " c->unparse = %(s)s_unparse_%(c)s;" % d
854 print "}"
c3bb4bd7
BP
855
856 # Table classes.
857 print "\f"
979821c0 858 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
bd76d25d 859 for tableName, table in sorted(schema.tables.iteritems()):
c3bb4bd7 860 structName = "%s%s" % (prefix, tableName.lower())
c5f341ab
BP
861 if table.is_root:
862 is_root = "true"
863 else:
864 is_root = "false"
865 print " {\"%s\", %s," % (tableName, is_root)
c3bb4bd7
BP
866 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
867 structName, structName)
a699f614 868 print " sizeof(struct %s), %s_init__}," % (structName, structName)
c3bb4bd7
BP
869 print "};"
870
871 # IDL class.
872 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
9cb53f26
BP
873 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
874 schema.name, prefix, prefix)
c3bb4bd7 875 print "};"
d879a707 876
bd76d25d
BP
877 # global init function
878 print """
879void
880%sinit(void)
881{
882 if (inited) {
883 return;
884 }
558103f0 885 assert_single_threaded();
bd76d25d
BP
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
87412f02
JP
893 print """
894/* Return the schema version. The caller must not free the returned value. */
895const char *
896%sget_db_version(void)
897{
898 return "%s";
899}
900""" % (prefix, schema.version)
901
902
8cdf0349 903
d879a707
BP
904def ovsdb_escape(string):
905 def escape(match):
906 c = match.group(0)
907 if c == '\0':
99155935 908 raise ovs.db.error.Error("strings may not contain null bytes")
d879a707
BP
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
d879a707
BP
925def usage():
926 print """\
927%(argv0)s: ovsdb schema compiler
00732bf5 928usage: %(argv0)s [OPTIONS] COMMAND ARG...
d879a707 929
00732bf5
BP
930The 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
89365653 934 nroff IDL print schema documentation in nroff format
d879a707
BP
935
936The 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
942if __name__ == "__main__":
943 try:
944 try:
00732bf5
BP
945 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
946 ['directory',
947 'help',
d879a707
BP
948 'version'])
949 except getopt.GetoptError, geo:
950 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
951 sys.exit(1)
c5c7c7c5 952
00732bf5
BP
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)
c5c7c7c5 962
d879a707 963 optKeys = [key for key, value in options]
00732bf5
BP
964
965 if not args:
966 sys.stderr.write("%s: missing command argument "
967 "(use --help for help)\n" % argv0)
d879a707
BP
968 sys.exit(1)
969
00732bf5
BP
970 commands = {"annotate": (annotateSchema, 2),
971 "c-idl-header": (printCIDLHeader, 1),
2c84fdf2 972 "c-idl-source": (printCIDLSource, 1)}
00732bf5
BP
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]))
d879a707 977 sys.exit(1)
00732bf5
BP
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:])
99155935
BP
987 except ovs.db.error.Error, e:
988 sys.stderr.write("%s: %s\n" % (argv0, e))
d879a707
BP
989 sys.exit(1)
990
991# Local variables:
992# mode: python
993# End: