]> git.proxmox.com Git - mirror_ovs.git/blame - ovsdb/ovsdb-idlc.in
datapath: Fix tunnel reconfiguration that does not change key data.
[mirror_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)
d879a707 21
02630ff2 22def constify(cType, const):
c667d679 23 if (const and cType.endswith('*') and not cType.endswith('**')):
02630ff2
BP
24 return 'const %s' % cType
25 else:
26 return cType
27
28def cMembers(prefix, columnName, column, const):
475281c0 29 type = column.type
7fae24e6
BP
30 if is_optional_bool(type):
31 const = True
99155935 32 if type.n_min == 1 and type.n_max == 1:
475281c0
BP
33 singleton = True
34 pointer = ''
35 else:
36 singleton = False
99155935 37 if type.is_optional_pointer():
475281c0
BP
38 pointer = ''
39 else:
40 pointer = '*'
41
42 if type.value:
43 key = {'name': "key_%s" % columnName,
bd76d25d 44 'type': constify(type.key.toCType(prefix) + pointer, const),
475281c0
BP
45 'comment': ''}
46 value = {'name': "value_%s" % columnName,
bd76d25d 47 'type': constify(type.value.toCType(prefix) + pointer, const),
475281c0
BP
48 'comment': ''}
49 members = [key, value]
50 else:
51 m = {'name': columnName,
bd76d25d
BP
52 'type': constify(type.key.toCType(prefix) + pointer, const),
53 'comment': type.cDeclComment()}
475281c0
BP
54 members = [m]
55
99155935 56 if not singleton and not type.is_optional_pointer():
475281c0
BP
57 members.append({'name': 'n_%s' % columnName,
58 'type': 'size_t ',
59 'comment': ''})
60 return members
61
00732bf5
BP
62def printCIDLHeader(schemaFile):
63 schema = parseSchema(schemaFile)
c3bb4bd7 64 prefix = schema.idlPrefix
d879a707
BP
65 print '''\
66/* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
67
68#ifndef %(prefix)sIDL_HEADER
69#define %(prefix)sIDL_HEADER 1
70
71#include <stdbool.h>
72#include <stddef.h>
73#include <stdint.h>
a6ec9089 74#include "ovsdb-data.h"
c3bb4bd7 75#include "ovsdb-idl-provider.h"
d879a707 76#include "uuid.h"''' % {'prefix': prefix.upper()}
979821c0 77
bd76d25d 78 for tableName, table in sorted(schema.tables.iteritems()):
c3bb4bd7 79 structName = "%s%s" % (prefix, tableName.lower())
979821c0
BP
80
81 print "\f"
82 print "/* %s table. */" % tableName
c3bb4bd7
BP
83 print "struct %s {" % structName
84 print "\tstruct ovsdb_idl_row header_;"
bd76d25d 85 for columnName, column in sorted(table.columns.iteritems()):
d879a707 86 print "\n\t/* %s column. */" % columnName
02630ff2 87 for member in cMembers(prefix, columnName, column, False):
475281c0 88 print "\t%(type)s%(name)s;%(comment)s" % member
979821c0 89 print "};"
c3bb4bd7 90
979821c0
BP
91 # Column indexes.
92 printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
bd76d25d 93 for columnName in sorted(table.columns)]
979821c0
BP
94 + ["%s_N_COLUMNS" % structName.upper()])
95
96 print
97 for columnName in table.columns:
98 print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
99 's': structName,
100 'S': structName.upper(),
101 'c': columnName,
102 'C': columnName.upper()}
103
104 print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
105
106 print '''
c3bb4bd7
BP
107const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
108const struct %(s)s *%(s)s_next(const struct %(s)s *);
58bc1a52
BP
109#define %(S)s_FOR_EACH(ROW, IDL) \\
110 for ((ROW) = %(s)s_first(IDL); \\
111 (ROW); \\
112 (ROW) = %(s)s_next(ROW))
113#define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
114 for ((ROW) = %(s)s_first(IDL); \\
115 (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
116 (ROW) = (NEXT))
475281c0
BP
117
118void %(s)s_delete(const struct %(s)s *);
119struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
120''' % {'s': structName, 'S': structName.upper()}
121
bd76d25d 122 for columnName, column in sorted(table.columns.iteritems()):
475281c0
BP
123 print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
124
a6ec9089
BP
125 print """
126/* Functions for fetching columns as \"struct ovsdb_datum\"s. (This is
127 rarely useful. More often, it is easier to access columns by using
128 the members of %(s)s directly.) */""" % {'s': structName}
129 for columnName, column in sorted(table.columns.iteritems()):
130 if column.type.value:
131 valueParam = ', enum ovsdb_atomic_type value_type'
132 else:
133 valueParam = ''
134 print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
135 's': structName, 'c': columnName, 'v': valueParam}
136
475281c0 137 print
bd76d25d 138 for columnName, column in sorted(table.columns.iteritems()):
475281c0
BP
139
140 print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
141 args = ['%(type)s%(name)s' % member for member
02630ff2 142 in cMembers(prefix, columnName, column, True)]
475281c0
BP
143 print '%s);' % ', '.join(args)
144
979821c0 145 # Table indexes.
bd76d25d 146 printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
979821c0
BP
147 print
148 for tableName in schema.tables:
149 print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
150 'p': prefix,
151 'P': prefix.upper(),
152 't': tableName.lower(),
153 'T': tableName.upper()}
154 print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
155
c3bb4bd7 156 print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
bd76d25d 157 print "\nvoid %sinit(void);" % prefix
c3bb4bd7
BP
158 print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
159
160def printEnum(members):
161 if len(members) == 0:
162 return
163
164 print "\nenum {";
165 for member in members[:-1]:
166 print " %s," % member
167 print " %s" % members[-1]
168 print "};"
169
7fae24e6
BP
170def is_optional_bool(type):
171 return (type.key.type == ovs.db.types.BooleanType and not type.value
172 and type.n_min == 0 and type.n_max == 1)
173
00732bf5
BP
174def printCIDLSource(schemaFile):
175 schema = parseSchema(schemaFile)
c3bb4bd7
BP
176 prefix = schema.idlPrefix
177 print '''\
178/* Generated automatically -- do not modify! -*- buffer-read-only: t -*- */
179
180#include <config.h>
181#include %s
bd76d25d 182#include <assert.h>
c3bb4bd7 183#include <limits.h>
bd76d25d
BP
184#include "ovsdb-data.h"
185#include "ovsdb-error.h"
186
187static bool inited;
89521e3f 188''' % schema.idlHeader
c3bb4bd7 189
66095e15 190 # Cast functions.
bd76d25d 191 for tableName, table in sorted(schema.tables.iteritems()):
66095e15
BP
192 structName = "%s%s" % (prefix, tableName.lower())
193 print '''
194static struct %(s)s *
979821c0 195%(s)s_cast(const struct ovsdb_idl_row *row)
66095e15
BP
196{
197 return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
198}\
199''' % {'s': structName}
200
201
bd76d25d 202 for tableName, table in sorted(schema.tables.iteritems()):
c3bb4bd7
BP
203 structName = "%s%s" % (prefix, tableName.lower())
204 print "\f"
2e57b537 205 print "/* %s table. */" % (tableName)
c3bb4bd7 206
979821c0 207 # Parse functions.
bd76d25d 208 for columnName, column in sorted(table.columns.iteritems()):
979821c0 209 print '''
c3bb4bd7 210static void
979821c0 211%(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
c3bb4bd7 212{
979821c0
BP
213 struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
214 'c': columnName}
c3bb4bd7 215
c3bb4bd7 216 type = column.type
c3bb4bd7
BP
217 if type.value:
218 keyVar = "row->key_%s" % columnName
219 valueVar = "row->value_%s" % columnName
220 else:
221 keyVar = "row->%s" % columnName
222 valueVar = None
223
7fae24e6
BP
224 if is_optional_bool(type):
225 # Special case for an optional bool. This is only here because
226 # sparse does not like the "normal" case below ("warning:
227 # expression using sizeof bool").
228 print
229 print " assert(inited);"
230 print " if (datum->n >= 1) {"
231 print " static const bool false_value = false;"
232 print " static const bool true_value = true;"
233 print
234 print " row->n_%s = 1;" % columnName
235 print " %s = datum->keys[0].boolean ? &true_value : &false_value;" % keyVar
236 print " } else {"
237 print " row->n_%s = 0;" % columnName
238 print " %s = NULL;" % keyVar
239 print " }"
240 elif (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
979821c0 241 print
bd76d25d 242 print " assert(inited);"
c3bb4bd7 243 print " if (datum->n >= 1) {"
99155935
BP
244 if not type.key.ref_table:
245 print " %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
c3bb4bd7 246 else:
7cba02e4 247 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
248
249 if valueVar:
99155935
BP
250 if type.value.ref_table:
251 print " %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
c3bb4bd7 252 else:
7cba02e4 253 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 254 print " } else {"
99155935 255 print " %s" % type.key.initCDefault(keyVar, type.n_min == 0)
979821c0 256 if valueVar:
99155935 257 print " %s" % type.value.initCDefault(valueVar, type.n_min == 0)
c3bb4bd7
BP
258 print " }"
259 else:
99155935
BP
260 if type.n_max != sys.maxint:
261 print " size_t n = MIN(%d, datum->n);" % type.n_max
979821c0 262 nMax = "n"
c3bb4bd7
BP
263 else:
264 nMax = "datum->n"
979821c0
BP
265 print " size_t i;"
266 print
bd76d25d 267 print " assert(inited);"
979821c0
BP
268 print " %s = NULL;" % keyVar
269 if valueVar:
270 print " %s = NULL;" % valueVar
271 print " row->n_%s = 0;" % columnName
c3bb4bd7
BP
272 print " for (i = 0; i < %s; i++) {" % nMax
273 refs = []
99155935 274 if type.key.ref_table:
7cba02e4 275 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
276 keySrc = "keyRow"
277 refs.append('keyRow')
278 else:
99155935
BP
279 keySrc = "datum->keys[i].%s" % type.key.type.to_string()
280 if type.value and type.value.ref_table:
7cba02e4 281 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
282 valueSrc = "valueRow"
283 refs.append('valueRow')
284 elif valueVar:
99155935 285 valueSrc = "datum->values[i].%s" % type.value.type.to_string()
c3bb4bd7
BP
286 if refs:
287 print " if (%s) {" % ' && '.join(refs)
288 indent = " "
289 else:
290 indent = " "
291 print "%sif (!row->n_%s) {" % (indent, columnName)
292 print "%s %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
293 if valueVar:
d78ac388 294 print "%s %s = xmalloc(%s * sizeof *%s);" % (indent, valueVar, nMax, valueVar)
c3bb4bd7
BP
295 print "%s}" % indent
296 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
297 if valueVar:
66095e15 298 print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
c3bb4bd7
BP
299 print "%srow->n_%s++;" % (indent, columnName)
300 if refs:
301 print " }"
302 print " }"
979821c0 303 print "}"
c3bb4bd7 304
979821c0 305 # Unparse functions.
bd76d25d 306 for columnName, column in sorted(table.columns.iteritems()):
c3bb4bd7 307 type = column.type
7fae24e6
BP
308 if (type.key.type == ovs.db.types.BooleanType and not type.value
309 and type.n_min == 0 and type.n_max == 1):
310 print '''
311static void
312%(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
313{
314 /* Nothing to do. */
315}''' % {'s': structName, 'c': columnName}
316 elif (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
979821c0 317 print '''
c3bb4bd7 318static void
979821c0 319%(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
c3bb4bd7 320{
979821c0 321 struct %(s)s *row = %(s)s_cast(row_);
bd76d25d
BP
322
323 assert(inited);''' % {'s': structName, 'c': columnName}
c3bb4bd7
BP
324 if type.value:
325 keyVar = "row->key_%s" % columnName
326 valueVar = "row->value_%s" % columnName
327 else:
328 keyVar = "row->%s" % columnName
329 valueVar = None
330 print " free(%s);" % keyVar
331 if valueVar:
332 print " free(%s);" % valueVar
979821c0
BP
333 print '}'
334 else:
335 print '''
c3bb4bd7 336static void
c69ee87c 337%(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
979821c0
BP
338{
339 /* Nothing to do. */
340}''' % {'s': structName, 'c': columnName}
c5c7c7c5 341
c3bb4bd7
BP
342 # First, next functions.
343 print '''
66095e15
BP
344const struct %(s)s *
345%(s)s_first(const struct ovsdb_idl *idl)
c3bb4bd7 346{
66095e15 347 return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
c3bb4bd7
BP
348}
349
66095e15
BP
350const struct %(s)s *
351%(s)s_next(const struct %(s)s *row)
c3bb4bd7 352{
66095e15 353 return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
475281c0
BP
354}''' % {'s': structName,
355 'p': prefix,
356 'P': prefix.upper(),
357 'T': tableName.upper()}
358
359 print '''
360void
9e336f49 361%(s)s_delete(const struct %(s)s *row)
475281c0 362{
475281c0
BP
363 ovsdb_idl_txn_delete(&row->header_);
364}
365
366struct %(s)s *
367%(s)s_insert(struct ovsdb_idl_txn *txn)
368{
ce5a3e38 369 return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
475281c0
BP
370}
371''' % {'s': structName,
372 'p': prefix,
373 'P': prefix.upper(),
374 'T': tableName.upper()}
375
376 # Verify functions.
bd76d25d 377 for columnName, column in sorted(table.columns.iteritems()):
475281c0
BP
378 print '''
379void
380%(s)s_verify_%(c)s(const struct %(s)s *row)
381{
bd76d25d 382 assert(inited);
475281c0
BP
383 ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
384}''' % {'s': structName,
385 'S': structName.upper(),
386 'c': columnName,
387 'C': columnName.upper()}
388
a6ec9089
BP
389 # Get functions.
390 for columnName, column in sorted(table.columns.iteritems()):
391 if column.type.value:
392 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
393 valueType = '\n assert(value_type == %s);' % column.type.value.toAtomicType()
394 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
395 else:
396 valueParam = ''
397 valueType = ''
398 valueComment = ''
399 print """
400/* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
401 * This is useful occasionally: for example, ovsdb_datum_find_key() is an
402 * easier and more efficient way to search for a given key than implementing
403 * the same operation on the "cooked" form in 'row'.
404 *
405 * 'key_type' must be %(kt)s.%(vc)s
406 * (This helps to avoid silent bugs if someone changes %(c)s's
407 * type without updating the caller.)
408 *
409 * The caller must not modify or free the returned value.
410 *
411 * Various kinds of changes can invalidate the returned value: modifying
412 * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
413 * If the returned value is needed for a long time, it is best to make a copy
414 * of it with ovsdb_datum_clone(). */
415const struct ovsdb_datum *
416%(s)s_get_%(c)s(const struct %(s)s *row,
417\tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
418{
419 assert(key_type == %(kt)s);%(vt)s
420 return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
421}""" % {'s': structName, 'c': columnName,
422 'kt': column.type.key.toAtomicType(),
423 'v': valueParam, 'vt': valueType, 'vc': valueComment}
424
475281c0 425 # Set functions.
bd76d25d 426 for columnName, column in sorted(table.columns.iteritems()):
475281c0
BP
427 type = column.type
428 print '\nvoid'
02630ff2 429 members = cMembers(prefix, columnName, column, True)
475281c0
BP
430 keyVar = members[0]['name']
431 nVar = None
432 valueVar = None
433 if type.value:
434 valueVar = members[1]['name']
435 if len(members) > 2:
436 nVar = members[2]['name']
437 else:
438 if len(members) > 1:
439 nVar = members[1]['name']
979821c0 440 print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
475281c0
BP
441 {'s': structName, 'c': columnName,
442 'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
443 print "{"
475281c0 444 print " struct ovsdb_datum datum;"
99155935 445 if type.n_min == 1 and type.n_max == 1:
475281c0 446 print
bd76d25d 447 print " assert(inited);"
475281c0
BP
448 print " datum.n = 1;"
449 print " datum.keys = xmalloc(sizeof *datum.keys);"
99155935 450 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
475281c0
BP
451 if type.value:
452 print " datum.values = xmalloc(sizeof *datum.values);"
99155935 453 print " "+ type.value.copyCValue("datum.values[0].%s" % type.value.type.to_string(), valueVar)
475281c0
BP
454 else:
455 print " datum.values = NULL;"
99155935 456 elif type.is_optional_pointer():
475281c0 457 print
bd76d25d 458 print " assert(inited);"
475281c0
BP
459 print " if (%s) {" % keyVar
460 print " datum.n = 1;"
461 print " datum.keys = xmalloc(sizeof *datum.keys);"
99155935 462 print " " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
475281c0
BP
463 print " } else {"
464 print " datum.n = 0;"
465 print " datum.keys = NULL;"
466 print " }"
467 print " datum.values = NULL;"
468 else:
469 print " size_t i;"
470 print
bd76d25d 471 print " assert(inited);"
475281c0
BP
472 print " datum.n = %s;" % nVar
473 print " datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
474 if type.value:
475 print " datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
476 else:
477 print " datum.values = NULL;"
478 print " for (i = 0; i < %s; i++) {" % nVar
99155935 479 print " " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
475281c0 480 if type.value:
99155935 481 print " " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
475281c0 482 print " }"
a1ec42a3
BP
483 if type.value:
484 valueType = type.value.toAtomicType()
485 else:
486 valueType = "OVSDB_TYPE_VOID"
487 print " ovsdb_datum_sort_unique(&datum, %s, %s);" % (
488 type.key.toAtomicType(), valueType)
475281c0
BP
489 print " ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
490 % {'s': structName,
491 'S': structName.upper(),
492 'C': columnName.upper()}
493 print "}"
c3bb4bd7
BP
494
495 # Table columns.
bd76d25d 496 print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
c3bb4bd7 497 structName, structName.upper())
bd76d25d
BP
498 print """
499static void\n%s_columns_init(void)
500{
501 struct ovsdb_idl_column *c;\
502""" % structName
503 for columnName, column in sorted(table.columns.iteritems()):
504 cs = "%s_col_%s" % (structName, columnName)
505 d = {'cs': cs, 'c': columnName, 's': structName}
506 print
507 print " /* Initialize %(cs)s. */" % d
508 print " c = &%(cs)s;" % d
509 print " c->name = \"%(c)s\";" % d
510 print column.type.cInitType(" ", "c->type")
511 print " c->parse = %(s)s_parse_%(c)s;" % d
512 print " c->unparse = %(s)s_unparse_%(c)s;" % d
513 print "}"
c3bb4bd7
BP
514
515 # Table classes.
516 print "\f"
979821c0 517 print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
bd76d25d 518 for tableName, table in sorted(schema.tables.iteritems()):
c3bb4bd7 519 structName = "%s%s" % (prefix, tableName.lower())
c5f341ab
BP
520 if table.is_root:
521 is_root = "true"
522 else:
523 is_root = "false"
524 print " {\"%s\", %s," % (tableName, is_root)
c3bb4bd7
BP
525 print " %s_columns, ARRAY_SIZE(%s_columns)," % (
526 structName, structName)
979821c0 527 print " sizeof(struct %s)}," % structName
c3bb4bd7
BP
528 print "};"
529
530 # IDL class.
531 print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
9cb53f26
BP
532 print " \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
533 schema.name, prefix, prefix)
c3bb4bd7 534 print "};"
d879a707 535
bd76d25d
BP
536 # global init function
537 print """
538void
539%sinit(void)
540{
541 if (inited) {
542 return;
543 }
544 inited = true;
545""" % prefix
546 for tableName, table in sorted(schema.tables.iteritems()):
547 structName = "%s%s" % (prefix, tableName.lower())
548 print " %s_columns_init();" % structName
549 print "}"
550
8cdf0349
BP
551def print_python_module(schema_file):
552 schema = ovs.db.schema.DbSchema.from_json(ovs.json.from_file(schema_file))
553 print """\
554# Generated automatically -- do not modify! -*- buffer-read-only: t -*-
555
556import ovs.db.schema
557import ovs.json
558
559__schema_json = \"\"\"
560%s
561\"\"\"
562
563schema = ovs.db.schema.DbSchema.from_json(ovs.json.from_string(__schema_json))
564""" % ovs.json.to_string(schema.to_json(), pretty=True)
565
d879a707
BP
566def ovsdb_escape(string):
567 def escape(match):
568 c = match.group(0)
569 if c == '\0':
99155935 570 raise ovs.db.error.Error("strings may not contain null bytes")
d879a707
BP
571 elif c == '\\':
572 return '\\\\'
573 elif c == '\n':
574 return '\\n'
575 elif c == '\r':
576 return '\\r'
577 elif c == '\t':
578 return '\\t'
579 elif c == '\b':
580 return '\\b'
581 elif c == '\a':
582 return '\\a'
583 else:
584 return '\\x%02x' % ord(c)
585 return re.sub(r'["\\\000-\037]', escape, string)
586
d879a707
BP
587def usage():
588 print """\
589%(argv0)s: ovsdb schema compiler
00732bf5 590usage: %(argv0)s [OPTIONS] COMMAND ARG...
d879a707 591
00732bf5
BP
592The following commands are supported:
593 annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
594 c-idl-header IDL print C header file for IDL
595 c-idl-source IDL print C source file for IDL implementation
8cdf0349 596 python-module IDL print Python module for IDL
89365653 597 nroff IDL print schema documentation in nroff format
d879a707
BP
598
599The following options are also available:
600 -h, --help display this help message
601 -V, --version display version information\
602""" % {'argv0': argv0}
603 sys.exit(0)
604
605if __name__ == "__main__":
606 try:
607 try:
00732bf5
BP
608 options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
609 ['directory',
610 'help',
d879a707
BP
611 'version'])
612 except getopt.GetoptError, geo:
613 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
614 sys.exit(1)
c5c7c7c5 615
00732bf5
BP
616 for key, value in options:
617 if key in ['-h', '--help']:
618 usage()
619 elif key in ['-V', '--version']:
620 print "ovsdb-idlc (Open vSwitch) @VERSION@"
621 elif key in ['-C', '--directory']:
622 os.chdir(value)
623 else:
624 sys.exit(0)
c5c7c7c5 625
d879a707 626 optKeys = [key for key, value in options]
00732bf5
BP
627
628 if not args:
629 sys.stderr.write("%s: missing command argument "
630 "(use --help for help)\n" % argv0)
d879a707
BP
631 sys.exit(1)
632
00732bf5
BP
633 commands = {"annotate": (annotateSchema, 2),
634 "c-idl-header": (printCIDLHeader, 1),
8cdf0349
BP
635 "c-idl-source": (printCIDLSource, 1),
636 "python-module": (print_python_module, 1)}
00732bf5
BP
637
638 if not args[0] in commands:
639 sys.stderr.write("%s: unknown command \"%s\" "
640 "(use --help for help)\n" % (argv0, args[0]))
d879a707 641 sys.exit(1)
00732bf5
BP
642
643 func, n_args = commands[args[0]]
644 if len(args) - 1 != n_args:
645 sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
646 "provided\n"
647 % (argv0, args[0], n_args, len(args) - 1))
648 sys.exit(1)
649
650 func(*args[1:])
99155935
BP
651 except ovs.db.error.Error, e:
652 sys.stderr.write("%s: %s\n" % (argv0, e))
d879a707
BP
653 sys.exit(1)
654
655# Local variables:
656# mode: python
657# End: