gitignore: Add ovsdbmonitor.
[sliver-openvswitch.git] / ovsdb / ovsdb-doc
1 #! /usr/bin/python
2
3 from datetime import date
4 import getopt
5 import os
6 import re
7 import sys
8 import xml.dom.minidom
9
10 import ovs.json
11 from ovs.db import error
12 import ovs.db.schema
13
14 argv0 = sys.argv[0]
15
16 def textToNroff(s, font=r'\fR'):
17     def escape(match):
18         c = match.group(0)
19         if c.startswith('-'):
20             if c != '-' or font == r'\fB':
21                 return '\\' + c
22             else:
23                 return '-'
24         if c == '\\':
25             return r'\e'
26         elif c == '"':
27             return r'\(dq'
28         elif c == "'":
29             return r'\(cq'
30         else:
31             raise error.Error("bad escape")
32
33     # Escape - \ " ' as needed by nroff.
34     s = re.sub('(-[0-9]|[-"\'\\\\])', escape, s)
35     if s.startswith('.'):
36         s = '\\' + s
37     return s
38
39 def escapeNroffLiteral(s):
40     return r'\fB%s\fR' % textToNroff(s, r'\fB')
41
42 def inlineXmlToNroff(node, font):
43     if node.nodeType == node.TEXT_NODE:
44         return textToNroff(node.data, font)
45     elif node.nodeType == node.ELEMENT_NODE:
46         if node.tagName in ['code', 'em', 'option']:
47             s = r'\fB'
48             for child in node.childNodes:
49                 s += inlineXmlToNroff(child, r'\fB')
50             return s + font
51         elif node.tagName == 'ref':
52             s = r'\fB'
53             if node.hasAttribute('column'):
54                 s += node.attributes['column'].nodeValue
55                 if node.hasAttribute('key'):
56                     s += ':' + node.attributes['key'].nodeValue
57             elif node.hasAttribute('table'):
58                 s += node.attributes['table'].nodeValue
59             elif node.hasAttribute('group'):
60                 s += node.attributes['group'].nodeValue
61             else:
62                 raise error.Error("'ref' lacks required attributes: %s" % node.attributes.keys())
63             return s + font
64         elif node.tagName == 'var':
65             s = r'\fI'
66             for child in node.childNodes:
67                 s += inlineXmlToNroff(child, r'\fI')
68             return s + font
69         else:
70             raise error.Error("element <%s> unknown or invalid here" % node.tagName)
71     else:
72         raise error.Error("unknown node %s in inline xml" % node)
73
74 def blockXmlToNroff(nodes, para='.PP'):
75     s = ''
76     for node in nodes:
77         if node.nodeType == node.TEXT_NODE:
78             s += textToNroff(node.data)
79             s = s.lstrip()
80         elif node.nodeType == node.ELEMENT_NODE:
81             if node.tagName in ['ul', 'ol']:
82                 if s != "":
83                     s += "\n"
84                 s += ".RS\n"
85                 i = 0
86                 for liNode in node.childNodes:
87                     if (liNode.nodeType == node.ELEMENT_NODE
88                         and liNode.tagName == 'li'):
89                         i += 1
90                         if node.tagName == 'ul':
91                             s += ".IP \\(bu\n"
92                         else:
93                             s += ".IP %d. .25in\n" % i
94                         s += blockXmlToNroff(liNode.childNodes, ".IP")
95                     elif (liNode.nodeType != node.TEXT_NODE
96                           or not liNode.data.isspace()):
97                         raise error.Error("<%s> element may only have <li> children" % node.tagName)
98                 s += ".RE\n"
99             elif node.tagName == 'dl':
100                 if s != "":
101                     s += "\n"
102                 s += ".RS\n"
103                 prev = "dd"
104                 for liNode in node.childNodes:
105                     if (liNode.nodeType == node.ELEMENT_NODE
106                         and liNode.tagName == 'dt'):
107                         if prev == 'dd':
108                             s += '.TP\n'
109                         else:
110                             s += '.TQ\n'
111                         prev = 'dt'
112                     elif (liNode.nodeType == node.ELEMENT_NODE
113                           and liNode.tagName == 'dd'):
114                         if prev == 'dd':
115                             s += '.IP\n'
116                         prev = 'dd'
117                     elif (liNode.nodeType != node.TEXT_NODE
118                           or not liNode.data.isspace()):
119                         raise error.Error("<dl> element may only have <dt> and <dd> children")
120                     s += blockXmlToNroff(liNode.childNodes, ".IP")
121                 s += ".RE\n"
122             elif node.tagName == 'p':
123                 if s != "":
124                     if not s.endswith("\n"):
125                         s += "\n"
126                     s += para + "\n"
127                 s += blockXmlToNroff(node.childNodes, para)
128             elif node.tagName in ('h1', 'h2', 'h3'):
129                 if s != "":
130                     if not s.endswith("\n"):
131                         s += "\n"
132                 nroffTag = {'h1': 'SH', 'h2': 'SS', 'h3': 'ST'}[node.tagName]
133                 s += ".%s " % nroffTag
134                 for child_node in node.childNodes:
135                     s += inlineXmlToNroff(child_node, r'\fR')
136                 s += "\n"
137             else:
138                 s += inlineXmlToNroff(node, r'\fR')
139         else:
140             raise error.Error("unknown node %s in block xml" % node)
141     if s != "" and not s.endswith('\n'):
142         s += '\n'
143     return s
144
145 def typeAndConstraintsToNroff(column):
146     type = column.type.toEnglish(escapeNroffLiteral)
147     constraints = column.type.constraintsToEnglish(escapeNroffLiteral,
148                                                    textToNroff)
149     if constraints:
150         type += ", " + constraints
151     if column.unique:
152         type += " (must be unique within table)"
153     return type
154
155 def columnGroupToNroff(table, groupXml):
156     introNodes = []
157     columnNodes = []
158     for node in groupXml.childNodes:
159         if (node.nodeType == node.ELEMENT_NODE
160             and node.tagName in ('column', 'group')):
161             columnNodes += [node]
162         else:
163             if (columnNodes
164                 and not (node.nodeType == node.TEXT_NODE
165                          and node.data.isspace())):
166                 raise error.Error("text follows <column> or <group> inside <group>: %s" % node)
167             introNodes += [node]
168
169     summary = []
170     intro = blockXmlToNroff(introNodes)
171     body = ''
172     for node in columnNodes:
173         if node.tagName == 'column':
174             name = node.attributes['name'].nodeValue
175             column = table.columns[name]
176             if node.hasAttribute('key'):
177                 key = node.attributes['key'].nodeValue
178                 if node.hasAttribute('type'):
179                     type_string = node.attributes['type'].nodeValue
180                     type_json = ovs.json.from_string(str(type_string))
181                     if type(type_json) in (str, unicode):
182                         raise error.Error("%s %s:%s has invalid 'type': %s" 
183                                           % (table.name, name, key, type_json))
184                     type_ = ovs.db.types.BaseType.from_json(type_json)
185                 else:
186                     type_ = column.type.value
187
188                 nameNroff = "%s : %s" % (name, key)
189
190                 if column.type.value:
191                     typeNroff = "optional %s" % column.type.value.toEnglish(
192                         escapeNroffLiteral)
193                     if (column.type.value.type == ovs.db.types.StringType and
194                         type_.type == ovs.db.types.BooleanType):
195                         # This is a little more explicit and helpful than
196                         # "containing a boolean"
197                         typeNroff += r", either \fBtrue\fR or \fBfalse\fR"
198                     else:
199                         if type_.type != column.type.value.type:
200                             type_english = type_.toEnglish()
201                             if type_english[0] in 'aeiou':
202                                 typeNroff += ", containing an %s" % type_english
203                             else:
204                                 typeNroff += ", containing a %s" % type_english
205                         constraints = (
206                             type_.constraintsToEnglish(escapeNroffLiteral,
207                                                        textToNroff))
208                         if constraints:
209                             typeNroff += ", %s" % constraints
210                 else:
211                     typeNroff = "none"
212             else:
213                 nameNroff = name
214                 typeNroff = typeAndConstraintsToNroff(column)
215             body += '.IP "\\fB%s\\fR: %s"\n' % (nameNroff, typeNroff)
216             body += blockXmlToNroff(node.childNodes, '.IP') + "\n"
217             summary += [('column', nameNroff, typeNroff)]
218         elif node.tagName == 'group':
219             title = node.attributes["title"].nodeValue
220             subSummary, subIntro, subBody = columnGroupToNroff(table, node)
221             summary += [('group', title, subSummary)]
222             body += '.ST "%s:"\n' % textToNroff(title)
223             body += subIntro + subBody
224         else:
225             raise error.Error("unknown element %s in <table>" % node.tagName)
226     return summary, intro, body
227
228 def tableSummaryToNroff(summary, level=0):
229     s = ""
230     for type, name, arg in summary:
231         if type == 'column':
232             s += ".TQ %.2fin\n\\fB%s\\fR\n%s\n" % (3 - level * .25, name, arg)
233         else:
234             s += ".TQ .25in\n\\fI%s:\\fR\n.RS .25in\n" % name
235             s += tableSummaryToNroff(arg, level + 1)
236             s += ".RE\n"
237     return s
238
239 def tableToNroff(schema, tableXml):
240     tableName = tableXml.attributes['name'].nodeValue
241     table = schema.tables[tableName]
242
243     s = """.bp
244 .SH "%s TABLE"
245 """ % tableName
246     summary, intro, body = columnGroupToNroff(table, tableXml)
247     s += intro
248     s += '.SS "Summary:\n'
249     s += tableSummaryToNroff(summary)
250     s += '.SS "Details:\n'
251     s += body
252     return s
253
254 def docsToNroff(schemaFile, xmlFile, erFile, title=None, version=None):
255     schema = ovs.db.schema.DbSchema.from_json(ovs.json.from_file(schemaFile))
256     doc = xml.dom.minidom.parse(xmlFile).documentElement
257
258     schemaDate = os.stat(schemaFile).st_mtime
259     xmlDate = os.stat(xmlFile).st_mtime
260     d = date.fromtimestamp(max(schemaDate, xmlDate))
261
262     if title == None:
263         title = schema.name
264
265     if version == None:
266         version = "UNKNOWN"
267
268     # Putting '\" p as the first line tells "man" that the manpage
269     # needs to be preprocessed by "pic".
270     s = r''''\" p
271 .TH "%s" 5 "%s" "Open vSwitch" "Open vSwitch Manual"
272 .\" -*- nroff -*-
273 .de TQ
274 .  br
275 .  ns
276 .  TP "\\$1"
277 ..
278 .de ST
279 .  PP
280 .  RS -0.15in
281 .  I "\\$1"
282 .  RE
283 ..
284 .SH NAME
285 %s \- %s database schema
286 .PP
287 ''' % (title, version, textToNroff(schema.name), schema.name)
288
289     tables = ""
290     introNodes = []
291     tableNodes = []
292     summary = []
293     for dbNode in doc.childNodes:
294         if (dbNode.nodeType == dbNode.ELEMENT_NODE
295             and dbNode.tagName == "table"):
296             tableNodes += [dbNode]
297
298             name = dbNode.attributes['name'].nodeValue
299             if dbNode.hasAttribute("title"):
300                 title = dbNode.attributes['title'].nodeValue
301             else:
302                 title = name + " configuration."
303             summary += [(name, title)]
304         else:
305             introNodes += [dbNode]
306
307     s += blockXmlToNroff(introNodes) + "\n"
308
309     s += r"""
310 .SH "TABLE SUMMARY"
311 .PP
312 The following list summarizes the purpose of each of the tables in the
313 \fB%s\fR database.  Each table is described in more detail on a later
314 page.
315 .IP "Table" 1in
316 Purpose
317 """ % schema.name
318     for name, title in summary:
319         s += r"""
320 .TQ 1in
321 \fB%s\fR
322 %s
323 """ % (name, textToNroff(title))
324
325     if erFile:
326         s += """
327 .\\" check if in troff mode (TTY)
328 .if t \{
329 .bp
330 .SH "TABLE RELATIONSHIPS"
331 .PP
332 The following diagram shows the relationship among tables in the
333 database.  Each node represents a table.  Tables that are part of the
334 ``root set'' are shown with double borders.  Each edge leads from the
335 table that contains it and points to the table that its value
336 represents.  Edges are labeled with their column names, followed by a
337 constraint on the number of allowed values: \\fB?\\fR for zero or one,
338 \\fB*\\fR for zero or more, \\fB+\\fR for one or more.  Thick lines
339 represent strong references; thin lines represent weak references.
340 .RS -1in
341 """
342         erStream = open(erFile, "r")
343         for line in erStream:
344             s += line + '\n'
345         erStream.close()
346         s += ".RE\\}\n"
347
348     for node in tableNodes:
349         s += tableToNroff(schema, node) + "\n"
350     return s
351
352 def usage():
353     print """\
354 %(argv0)s: ovsdb schema documentation generator
355 Prints documentation for an OVSDB schema as an nroff-formatted manpage.
356 usage: %(argv0)s [OPTIONS] SCHEMA XML
357 where SCHEMA is an OVSDB schema in JSON format
358   and XML is OVSDB documentation in XML format.
359
360 The following options are also available:
361   --er-diagram=DIAGRAM.PIC    include E-R diagram from DIAGRAM.PIC
362   --title=TITLE               use TITLE as title instead of schema name
363   --version=VERSION           use VERSION to display on document footer
364   -h, --help                  display this help message\
365 """ % {'argv0': argv0}
366     sys.exit(0)
367
368 if __name__ == "__main__":
369     try:
370         try:
371             options, args = getopt.gnu_getopt(sys.argv[1:], 'hV',
372                                               ['er-diagram=', 'title=',
373                                                'version=', 'help'])
374         except getopt.GetoptError, geo:
375             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
376             sys.exit(1)
377
378         er_diagram = None
379         title = None
380         version = None
381         for key, value in options:
382             if key == '--er-diagram':
383                 er_diagram = value
384             elif key == '--title':
385                 title = value
386             elif key == '--version':
387                 version = value
388             elif key in ['-h', '--help']:
389                 usage()
390             else:
391                 sys.exit(0)
392
393         if len(args) != 2:
394             sys.stderr.write("%s: exactly 2 non-option arguments required "
395                              "(use --help for help)\n" % argv0)
396             sys.exit(1)
397
398         # XXX we should warn about undocumented tables or columns
399         s = docsToNroff(args[0], args[1], er_diagram, title, version)
400         for line in s.split("\n"):
401             line = line.strip()
402             if len(line):
403                 print line
404
405     except error.Error, e:
406         sys.stderr.write("%s: %s\n" % (argv0, e.msg))
407         sys.exit(1)
408
409 # Local variables:
410 # mode: python
411 # End: