179353035d9f044231134d43f50c8ef9af5388e8
[sliver-openvswitch.git] / ovsdb / ovsdb-dot.in
1 #! @PYTHON@
2
3 from datetime import date
4 import getopt
5 import os
6 import re
7 import sys
8
9 sys.path.insert(0, "@abs_top_srcdir@/ovsdb")
10 import simplejson as json
11
12 from OVSDB import *
13
14 argv0 = sys.argv[0]
15
16 def printEdge(tableName, baseType, label):
17     if baseType.refTable:
18         options = {}
19         options['label'] = '"%s"' % label
20         if baseType.refType == 'weak':
21             options['constraint'] = 'false'
22         print "\t%s -> %s [%s];" % (
23             tableName,
24             baseType.refTable,
25             ', '.join(['%s=%s' % (k,v) for k,v in options.items()]))
26
27 def schemaToDot(schemaFile):
28     schema = DbSchema.fromJson(json.load(open(schemaFile, "r")))
29
30     print "digraph %s {" % schema.name
31     for tableName, table in schema.tables.iteritems():
32         print '\tsize="6.5,4";'
33         print '\tmargin="0";'
34         print "\tnode [shape=box];"
35         print "\t%s;" % tableName
36         for columnName, column in table.columns.iteritems():
37             if column.type.value:
38                 printEdge(tableName, column.type.key, "%s key" % columnName)
39                 printEdge(tableName, column.type.value, "%s value" % columnName)
40             else:
41                 printEdge(tableName, column.type.key, columnName)
42     print "}";
43
44 def usage():
45     print """\
46 %(argv0)s: compiles ovsdb schemas to graphviz format
47 Prints a .dot file that "dot" can render to an entity-relationship diagram
48 usage: %(argv0)s [OPTIONS] SCHEMA
49 where SCHEMA is an OVSDB schema in JSON format
50
51 The following options are also available:
52   -h, --help                  display this help message
53   -V, --version               display version information\
54 """ % {'argv0': argv0}
55     sys.exit(0)
56
57 if __name__ == "__main__":
58     try:
59         try:
60             options, args = getopt.gnu_getopt(sys.argv[1:], 'hV',
61                                               ['help', 'version'])
62         except getopt.GetoptError, geo:
63             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
64             sys.exit(1)
65
66         for key, value in options:
67             if key in ['-h', '--help']:
68                 usage()
69             elif key in ['-V', '--version']:
70                 print "ovsdb-dot (Open vSwitch) @VERSION@"
71             else:
72                 sys.exit(0)
73             
74         if len(args) != 1:
75             sys.stderr.write("%s: exactly 1 non-option argument required "
76                              "(use --help for help)\n" % argv0)
77             sys.exit(1)
78
79         schemaToDot(args[0])
80         
81     except Error, e:
82         sys.stderr.write("%s: %s\n" % (argv0, e.msg))
83         sys.exit(1)
84
85 # Local variables:
86 # mode: python
87 # End: