system_messages.py 13 KB

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