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