system_messages.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. # Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. #
  3. # Permission to use, copy, modify, and/or distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. # PERFORMANCE OF THIS SOFTWARE.
  14. # Produce System Messages Manual
  15. #
  16. # This tool reads all the .mes files in the directory tree whose root is given
  17. # on the command line and interprets them as BIND 10 message files. It pulls
  18. # all the messages and description out, sorts them by message ID, and writes
  19. # them out as a single (formatted) file.
  20. #
  21. # Invocation:
  22. # The code is invoked using the command line:
  23. #
  24. # python system_messages.py [-o <output-file>] <top-source-directory>
  25. #
  26. # If no output file is specified, output is written to stdout.
  27. import re
  28. import os
  29. import sys
  30. from optparse import OptionParser
  31. # Main dictionary holding all the messages. The messages are accumulated here
  32. # before being printed in alphabetical order.
  33. dictionary = {}
  34. # The structure of the output page is:
  35. #
  36. # header
  37. # message
  38. # separator
  39. # message
  40. # separator
  41. # :
  42. # separator
  43. # message
  44. # trailer
  45. #
  46. # (Indentation is not relevant - it has only been added to the above
  47. # illustration to make the structure clearer.) The text of these section is:
  48. # Header - this is output before anything else.
  49. SEC_HEADER="""<?xml version="1.0" encoding="UTF-8"?>
  50. <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
  51. "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd" [
  52. <!ENTITY mdash "&#x2014;" >
  53. <!ENTITY % version SYSTEM "version.ent">
  54. %version;
  55. ]>
  56. <!--
  57. This XML document is generated using the system_messages.py tool
  58. based on the .mes message files.
  59. Do not edit this file.
  60. -->
  61. <book>
  62. <?xml-stylesheet href="bind10-guide.css" type="text/css"?>
  63. <bookinfo>
  64. <title>BIND 10 Messages Manual</title>
  65. <copyright>
  66. <year>2011</year><holder>Internet Systems Consortium, Inc.</holder>
  67. </copyright>
  68. <abstract>
  69. <para>BIND 10 is a Domain Name System (DNS) suite managed by
  70. Internet Systems Consortium (ISC). It includes DNS libraries
  71. and modular components for controlling authoritative and
  72. recursive DNS servers.
  73. </para>
  74. <para>
  75. This is the messages manual for BIND 10 version &__VERSION__;.
  76. The most up-to-date version of this document, along with
  77. other documents for BIND 10, can be found at
  78. <ulink url="http://bind10.isc.org/docs"/>.
  79. </para>
  80. </abstract>
  81. <releaseinfo>This is the messages manual for BIND 10 version
  82. &__VERSION__;.</releaseinfo>
  83. </bookinfo>
  84. <chapter id="intro">
  85. <title>Introduction</title>
  86. <para>
  87. This document lists each message that can be logged by the
  88. programs in the BIND 10 package. Each entry in this manual
  89. is of the form:
  90. <screen>IDENTIFICATION message-text</screen>
  91. ... where "IDENTIFICATION" is the message identification included
  92. in each message logged and "message-text" is the accompanying
  93. message text. The "message-text" may include placeholders of the
  94. form "%1", "%2" etc.; these parameters are replaced by relevant
  95. values when the message is logged.
  96. </para>
  97. <para>
  98. Each entry is also accompanied by a description giving more
  99. information about the circumstances that result in the message
  100. being logged.
  101. </para>
  102. <para>
  103. For information on configuring and using BIND 10 logging,
  104. refer to the <ulink url="bind10-guide.html">BIND 10 Guide</ulink>.
  105. </para>
  106. </chapter>
  107. <chapter id="messages">
  108. <title>BIND 10 Messages</title>
  109. <para>
  110. <variablelist>
  111. """
  112. # This is output once for each message. The string contains substitution
  113. # tokens: $I is replaced by the message identification, $T by the message text,
  114. # and $D by the message description.
  115. SEC_MESSAGE = """<varlistentry id="$I">
  116. <term>$I $T</term>
  117. <listitem><para>
  118. $D
  119. </para></listitem>
  120. </varlistentry>"""
  121. # A description may contain blank lines intended to separate paragraphs. If so,
  122. # each blank line is replaced by the following.
  123. SEC_BLANK = "</para><para>"
  124. # The separator is copied to the output verbatim after each message except
  125. # the last.
  126. SEC_SEPARATOR = ""
  127. # The trailier is copied to the output verbatim after the last message.
  128. SEC_TRAILER = """ </variablelist>
  129. </para>
  130. </chapter>
  131. </book>"""
  132. def reportError(filename, what):
  133. """Report an error and exit"""
  134. print("*** ERROR in ", filename, file=sys.stderr)
  135. print("*** REASON: ", what, file=sys.stderr)
  136. print("*** System message generator terminating", file=sys.stderr)
  137. sys.exit(1)
  138. def replaceTag(string):
  139. """Replaces the '<' and '>' in text about to be inserted into the template
  140. sections above with &lt; and &gt; to avoid problems with message text
  141. being interpreted as XML text.
  142. """
  143. string1 = string.replace("<", "&lt;")
  144. string2 = string1.replace(">", "&gt;")
  145. return string2
  146. def replaceBlankLines(lines):
  147. """Replaces blank lines in an array with the contents of the 'blank'
  148. section.
  149. """
  150. result = []
  151. for l in lines:
  152. if len(l) == 0:
  153. result.append(SEC_BLANK)
  154. else:
  155. result.append(l)
  156. return result
  157. # Printing functions
  158. def printHeader():
  159. print(SEC_HEADER)
  160. def printSeparator():
  161. print(SEC_SEPARATOR)
  162. def printMessage(msgid):
  163. # In the message ID, replace "<" and ">" with XML-safe versions and
  164. # substitute into the data.
  165. m1 = SEC_MESSAGE.replace("$I", replaceTag(msgid))
  166. # Do the same for the message text.
  167. m2 = m1.replace("$T", replaceTag(dictionary[msgid]['text']))
  168. # Do the same for the description then replace blank lines with the
  169. # specified separator. (We do this in that order to avoid replacing
  170. # the "<" and ">" in the XML tags in the separator.)
  171. desc1 = [replaceTag(l) for l in dictionary[msgid]['description']]
  172. desc2 = replaceBlankLines(desc1)
  173. # Join the lines together to form a single string and insert into
  174. # current text.
  175. m3 = m2.replace("$D", "\n".join(desc2))
  176. print(m3)
  177. def printTrailer():
  178. print(SEC_TRAILER)
  179. def removeEmptyLeadingTrailing(lines):
  180. """Removes leading and trailing empty lines.
  181. A list of strings is passed as argument, some of which may be empty.
  182. This function removes from the start and end of list a contiguous
  183. sequence of empty lines and returns the result. Embedded sequence of
  184. empty lines are not touched.
  185. Parameters:
  186. lines List of strings to be modified.
  187. Return:
  188. Input list of strings with leading/trailing blank line sequences
  189. removed.
  190. """
  191. retlines = []
  192. # Dispose of degenerate case of empty array
  193. if len(lines) == 0:
  194. return retlines
  195. # Search for first non-blank line
  196. start = 0
  197. while start < len(lines):
  198. if len(lines[start]) > 0:
  199. break
  200. start = start + 1
  201. # Handle case when entire list is empty
  202. if start >= len(lines):
  203. return retlines
  204. # Search for last non-blank line
  205. finish = len(lines) - 1
  206. while finish >= 0:
  207. if len(lines[finish]) > 0:
  208. break
  209. finish = finish - 1
  210. retlines = lines[start:finish + 1]
  211. return retlines
  212. def addToDictionary(msgid, msgtext, desc, filename):
  213. """Add the current message ID and associated information to the global
  214. dictionary. If a message with that ID already exists, loop appending
  215. suffixes of the form "(n)" to it until one is found that doesn't.
  216. Parameters:
  217. msgid Message ID
  218. msgtext Message text
  219. desc Message description
  220. filename File from which the message came. Currently this is
  221. not used, but a future enhancement may wish to include the
  222. name of the message file in the messages manual.
  223. """
  224. # If the ID is in the dictionary, append a "(n)" to the name - this wil
  225. # flag that there are multiple instances. (However, this is an error -
  226. # each ID should be unique in BIND-10.)
  227. if msgid in dictionary:
  228. i = 1
  229. while msgid + " (" + str(i) + ")" in dictionary:
  230. i = i + 1
  231. msgid = msgid + " (" + str(i) + ")"
  232. # Remove leading and trailing blank lines in the description, then
  233. # add everything into a subdictionary which is then added to the main
  234. # one.
  235. details = {}
  236. details['text'] = msgtext
  237. details['description'] = removeEmptyLeadingTrailing(desc)
  238. details['filename'] = filename
  239. dictionary[msgid] = details
  240. def processFileContent(filename, lines):
  241. """Processes file content. Messages and descriptions are identified and
  242. added to a dictionary (keyed by message ID). If the key already exists,
  243. a numeric suffix is added to it.
  244. Parameters:
  245. filename Name of the message file being processed
  246. lines Lines read from the file
  247. """
  248. prefix = "" # Last prefix encountered
  249. msgid = "" # Last message ID encountered
  250. msgtext = "" # Text of the message
  251. description = [] # Description
  252. for l in lines:
  253. if l.startswith("$"):
  254. # Starts with "$". Ignore anything other than $PREFIX
  255. words = re.split("\s+", l)
  256. if words[0].upper() == "$PREFIX":
  257. if len(words) == 1:
  258. prefix = ""
  259. else:
  260. prefix = words[1]
  261. elif l.startswith("%"):
  262. # Start of a message. Add the message we were processing to the
  263. # dictionary and clear everything apart from the file name.
  264. if msgid != "":
  265. addToDictionary(msgid, msgtext, description, filename)
  266. msgid = ""
  267. msgtext = ""
  268. description = []
  269. # Start of a message
  270. l = l[1:].strip() # Remove "%" and trim leading spaces
  271. if len(l) == 0:
  272. printError(filename, "Line with single % found")
  273. next
  274. # Split into words. The first word is the message ID
  275. words = re.split("\s+", l)
  276. msgid = (prefix + words[0]).upper()
  277. msgtext = l[len(words[0]):].strip()
  278. else:
  279. # Part of a description, so add to the current description array
  280. description.append(l)
  281. # All done, add the last message to the global dictionaty.
  282. if msgid != "":
  283. addToDictionary(msgid, msgtext, description, filename)
  284. def processFile(filename):
  285. """Processes a file by reading it in and stripping out all comments and
  286. and directives. Leading and trailing blank lines in the file are removed
  287. and the remainder passed for message processing.
  288. Parameters:
  289. filename Name of the message file to process
  290. """
  291. lines = open(filename).readlines();
  292. # Trim leading and trailing spaces from each line, and remove comments.
  293. lines = [l.strip() for l in lines]
  294. lines = [l for l in lines if not l.startswith("#")]
  295. # Remove leading/trailing empty line sequences from the result
  296. lines = removeEmptyLeadingTrailing(lines)
  297. # Interpret content
  298. processFileContent(filename, lines)
  299. def processAllFiles(root):
  300. """Iterates through all files in the tree starting at the given root and
  301. calls processFile for all .mes files found.
  302. Parameters:
  303. root Directory that is the root of the BIND-10 source tree
  304. """
  305. for (path, dirs, files) in os.walk(root):
  306. # Identify message files
  307. mes_files = [f for f in files if f.endswith(".mes")]
  308. # ... and process each file in the list
  309. for m in mes_files:
  310. processFile(path + os.sep + m)
  311. # Main program
  312. if __name__ == "__main__":
  313. parser = OptionParser(usage="Usage: %prog [--help | options] root")
  314. parser.add_option("-o", "--output", dest="output", default=None,
  315. metavar="FILE",
  316. help="output file name (default to stdout)")
  317. (options, args) = parser.parse_args()
  318. if len(args) == 0:
  319. parser.error("Must supply directory at which to begin search")
  320. elif len(args) > 1:
  321. parser.error("Only a single root directory can be given")
  322. # Redirect output if specified (errors are written to stderr)
  323. if options.output is not None:
  324. sys.stdout = open(options.output, 'w')
  325. # Read the files and load the data
  326. processAllFiles(args[0])
  327. # Now just print out everything we've read (in alphabetical order).
  328. count = 1
  329. printHeader()
  330. for msgid in sorted(dictionary):
  331. if count > 1:
  332. printSeparator()
  333. count = count + 1
  334. printMessage(msgid)
  335. printTrailer()