system_messages.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. <book>
  57. <?xml-stylesheet href="bind10-guide.css" type="text/css"?>
  58. <bookinfo>
  59. <title>BIND 10 Messages Manual</title>
  60. <copyright>
  61. <year>2011</year><holder>Internet Systems Consortium, Inc.</holder>
  62. </copyright>
  63. <abstract>
  64. <para>BIND 10 is a Domain Name System (DNS) suite managed by
  65. Internet Systems Consortium (ISC). It includes DNS libraries
  66. and modular components for controlling authoritative and
  67. recursive DNS servers.
  68. </para>
  69. <para>
  70. This is the messages manual for BIND 10 version &__VERSION__;.
  71. The most up-to-date version of this document, along with
  72. other documents for BIND 10, can be found at
  73. <ulink url="http://bind10.isc.org/docs"/>.
  74. </para>
  75. </abstract>
  76. <releaseinfo>This is the messages manual for BIND 10 version
  77. &__VERSION__;.</releaseinfo>
  78. </bookinfo>
  79. <chapter id="intro">
  80. <title>Introduction</title>
  81. <para>
  82. This document lists each message that can be logged by the
  83. programs in the BIND 10 package. Each entry in this manual
  84. is of the form:
  85. <screen>IDENTIFICATION message-text</screen>
  86. ... where "IDENTIFICATION" is the message identification included
  87. in each message logged and "message-text" is the accompanying
  88. message text. The "message-text" may include placeholders of the
  89. form "%1", "%2" etc.; these parameters are replaced by relevant
  90. values when the message is logged.
  91. </para>
  92. <para>
  93. Each entry is also accompanied by a description giving more
  94. information about the circumstances that result in the message
  95. being logged.
  96. </para>
  97. <para>
  98. For information on configuring and using BIND 10 logging,
  99. refer to the <ulink url="bind10-guide.html">BIND 10 Guide</ulink>.
  100. </para>
  101. </chapter>
  102. <chapter id="messages">
  103. <title>BIND 10 Messages</title>
  104. <para>
  105. <variablelist>
  106. """
  107. # This is output once for each message. The string contains substitution
  108. # tokens: $I is replaced by the message identification, $T by the message text,
  109. # and $D by the message description.
  110. SEC_MESSAGE = """<varlistentry id="$I">
  111. <term>$I $T</term>
  112. <listitem><para>
  113. $D
  114. </para></listitem>
  115. </varlistentry>"""
  116. # A description may contain blank lines intended to separate paragraphs. If so,
  117. # each blank line is replaced by the following.
  118. SEC_BLANK = "</para><para>"
  119. # The separator is copied to the output verbatim after each message except
  120. # the last.
  121. SEC_SEPARATOR = ""
  122. # The trailier is copied to the output verbatim after the last message.
  123. SEC_TRAILER = """ </variablelist>
  124. </para>
  125. </chapter>
  126. </book>
  127. """
  128. def reportError(filename, what):
  129. """Report an error and exit"""
  130. print("*** ERROR in ", filename, file=sys.stderr)
  131. print("*** REASON: ", what, file=sys.stderr)
  132. print("*** System message generator terminating", file=sys.stderr)
  133. sys.exit(1)
  134. def replaceTag(string):
  135. """Replaces the '<' and '>' in text about to be inserted into the template
  136. sections above with &lt; and &gt; to avoid problems with message text
  137. being interpreted as XML text.
  138. """
  139. string1 = string.replace("<", "&lt;")
  140. string2 = string1.replace(">", "&gt;")
  141. return string2
  142. def replaceBlankLines(lines):
  143. """Replaces blank lines in an array with the contents of the 'blank'
  144. section.
  145. """
  146. result = []
  147. for l in lines:
  148. if len(l) == 0:
  149. result.append(SEC_BLANK)
  150. else:
  151. result.append(l)
  152. return result
  153. # Printing functions
  154. def printHeader():
  155. print(SEC_HEADER)
  156. def printSeparator():
  157. print(SEC_SEPARATOR)
  158. def printMessage(msgid):
  159. # In the message ID, replace "<" and ">" with XML-safe versions and
  160. # substitute into the data.
  161. m1 = SEC_MESSAGE.replace("$I", replaceTag(msgid))
  162. # Do the same for the message text.
  163. m2 = m1.replace("$T", replaceTag(dictionary[msgid]['text']))
  164. # Do the same for the description then replace blank lines with the
  165. # specified separator. (We do this in that order to avoid replacing
  166. # the "<" and ">" in the XML tags in the separator.)
  167. desc1 = [replaceTag(l) for l in dictionary[msgid]['description']]
  168. desc2 = replaceBlankLines(desc1)
  169. # Join the lines together to form a single string and insert into
  170. # current text.
  171. m3 = m2.replace("$D", "\n".join(desc2))
  172. print(m3)
  173. def printTrailer():
  174. print(SEC_TRAILER)
  175. def removeEmptyLeadingTrailing(lines):
  176. """Removes leading and trailing empty lines.
  177. A list of strings is passed as argument, some of which may be empty.
  178. This function removes from the start and end of list a contiguous
  179. sequence of empty lines and returns the result. Embedded sequence of
  180. empty lines are not touched.
  181. Parameters:
  182. lines List of strings to be modified.
  183. Return:
  184. Input list of strings with leading/trailing blank line sequences
  185. removed.
  186. """
  187. retlines = []
  188. # Dispose of degenerate case of empty array
  189. if len(lines) == 0:
  190. return retlines
  191. # Search for first non-blank line
  192. start = 0
  193. while start < len(lines):
  194. if len(lines[start]) > 0:
  195. break
  196. start = start + 1
  197. # Handle case when entire list is empty
  198. if start >= len(lines):
  199. return retlines
  200. # Search for last non-blank line
  201. finish = len(lines) - 1
  202. while finish >= 0:
  203. if len(lines[finish]) > 0:
  204. break
  205. finish = finish - 1
  206. retlines = lines[start:finish + 1]
  207. return retlines
  208. def addToDictionary(msgid, msgtext, desc, filename):
  209. """Add the current message ID and associated information to the global
  210. dictionary. If a message with that ID already exists, loop appending
  211. suffixes of the form "(n)" to it until one is found that doesn't.
  212. Parameters:
  213. msgid Message ID
  214. msgtext Message text
  215. desc Message description
  216. filename File from which the message came. Currently this is
  217. not used, but a future enhancement may wish to include the
  218. name of the message file in the messages manual.
  219. """
  220. # If the ID is in the dictionary, append a "(n)" to the name - this wil
  221. # flag that there are multiple instances. (However, this is an error -
  222. # each ID should be unique in BIND-10.)
  223. if msgid in dictionary:
  224. i = 1
  225. while msgid + " (" + str(i) + ")" in dictionary:
  226. i = i + 1
  227. msgid = msgid + " (" + str(i) + ")"
  228. # Remove leading and trailing blank lines in the description, then
  229. # add everything into a subdictionary which is then added to the main
  230. # one.
  231. details = {}
  232. details['text'] = msgtext
  233. details['description'] = removeEmptyLeadingTrailing(desc)
  234. details['filename'] = filename
  235. dictionary[msgid] = details
  236. def processFileContent(filename, lines):
  237. """Processes file content. Messages and descriptions are identified and
  238. added to a dictionary (keyed by message ID). If the key already exists,
  239. a numeric suffix is added to it.
  240. Parameters:
  241. filename Name of the message file being processed
  242. lines Lines read from the file
  243. """
  244. prefix = "" # Last prefix encountered
  245. msgid = "" # Last message ID encountered
  246. msgtext = "" # Text of the message
  247. description = [] # Description
  248. for l in lines:
  249. if l.startswith("$"):
  250. # Starts with "$". Ignore anything other than $PREFIX
  251. words = re.split("\s+", l)
  252. if words[0].upper() == "$PREFIX":
  253. if len(words) == 1:
  254. prefix = ""
  255. else:
  256. prefix = words[1]
  257. elif l.startswith("%"):
  258. # Start of a message. Add the message we were processing to the
  259. # dictionary and clear everything apart from the file name.
  260. if msgid != "":
  261. addToDictionary(msgid, msgtext, description, filename)
  262. msgid = ""
  263. msgtext = ""
  264. description = []
  265. # Start of a message
  266. l = l[1:].strip() # Remove "%" and trim leading spaces
  267. if len(l) == 0:
  268. printError(filename, "Line with single % found")
  269. next
  270. # Split into words. The first word is the message ID
  271. words = re.split("\s+", l)
  272. msgid = (prefix + words[0]).upper()
  273. msgtext = l[len(words[0]):].strip()
  274. else:
  275. # Part of a description, so add to the current description array
  276. description.append(l)
  277. # All done, add the last message to the global dictionaty.
  278. if msgid != "":
  279. addToDictionary(msgid, msgtext, description, filename)
  280. def processFile(filename):
  281. """Processes a file by reading it in and stripping out all comments and
  282. and directives. Leading and trailing blank lines in the file are removed
  283. and the remainder passed for message processing.
  284. Parameters:
  285. filename Name of the message file to process
  286. """
  287. lines = open(filename).readlines();
  288. # Trim leading and trailing spaces from each line, and remove comments.
  289. lines = [l.strip() for l in lines]
  290. lines = [l for l in lines if not l.startswith("#")]
  291. # Remove leading/trailing empty line sequences from the result
  292. lines = removeEmptyLeadingTrailing(lines)
  293. # Interpret content
  294. processFileContent(filename, lines)
  295. def processAllFiles(root):
  296. """Iterates through all files in the tree starting at the given root and
  297. calls processFile for all .mes files found.
  298. Parameters:
  299. root Directory that is the root of the BIND-10 source tree
  300. """
  301. for (path, dirs, files) in os.walk(root):
  302. # Identify message files
  303. mes_files = [f for f in files if f.endswith(".mes")]
  304. # ... and process each file in the list
  305. for m in mes_files:
  306. processFile(path + os.sep + m)
  307. # Main program
  308. if __name__ == "__main__":
  309. parser = OptionParser(usage="Usage: %prog [--help | options] root")
  310. parser.add_option("-o", "--output", dest="output", default=None,
  311. metavar="FILE",
  312. help="output file name (default to stdout)")
  313. (options, args) = parser.parse_args()
  314. if len(args) == 0:
  315. parser.error("Must supply directory at which to begin search")
  316. elif len(args) > 1:
  317. parser.error("Only a single root directory can be given")
  318. # Redirect output if specified (errors are written to stderr)
  319. if options.output is not None:
  320. sys.stdout = open(options.output, 'w')
  321. # Read the files and load the data
  322. processAllFiles(args[0])
  323. # Now just print out everything we've read (in alphabetical order).
  324. count = 1
  325. printHeader()
  326. for msgid in sorted(dictionary):
  327. if count > 1:
  328. printSeparator()
  329. count = count + 1
  330. printMessage(msgid)
  331. printTrailer()