message.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. #include <cctype>
  15. #include <cstddef>
  16. #include <fstream>
  17. #include <iostream>
  18. #include <string>
  19. #include <vector>
  20. #include <errno.h>
  21. #include <getopt.h>
  22. #include <string.h>
  23. #include <time.h>
  24. #include <unistd.h>
  25. #include <util/filename.h>
  26. #include <util/strutil.h>
  27. #include <log/message_dictionary.h>
  28. #include <log/message_exception.h>
  29. #include <log/message_reader.h>
  30. #include <log/messagedef.h>
  31. #include <log/logger.h>
  32. #include <boost/foreach.hpp>
  33. using namespace std;
  34. using namespace isc::log;
  35. using namespace isc::util;
  36. static const char* VERSION = "1.0-0";
  37. /// \brief Message Compiler
  38. ///
  39. /// \b Overview<BR>
  40. /// This is the program that takes as input a message file and produces:
  41. ///
  42. /// \li A .h file containing message definition
  43. /// \li A .cc file containing code that adds the messages to the program's
  44. /// message dictionary at start-up time.
  45. ///
  46. /// \b Invocation<BR>
  47. /// The program is invoked with the command:
  48. ///
  49. /// <tt>message [-v | -h | \<message-file\>]</tt>
  50. ///
  51. /// It reads the message file and writes out two files of the same name in the
  52. /// default directory but with extensions of .h and .cc.
  53. ///
  54. /// \-v causes it to print the version number and exit. \-h prints a help
  55. /// message (and exits).
  56. /// \brief Print Version
  57. ///
  58. /// Prints the program's version number.
  59. void
  60. version() {
  61. cout << VERSION << "\n";
  62. }
  63. /// \brief Print Usage
  64. ///
  65. /// Prints program usage to stdout.
  66. void
  67. usage() {
  68. cout <<
  69. "Usage: message [-h] [-v] [-p] <message-file>\n" <<
  70. "\n" <<
  71. "-h Print this message and exit\n" <<
  72. "-v Print the program version and exit\n" <<
  73. "-p Output python source instead of C++ ones\n" <<
  74. "\n" <<
  75. "<message-file> is the name of the input message file.\n";
  76. }
  77. /// \brief Create Time
  78. ///
  79. /// Returns the current time as a suitably-formatted string.
  80. ///
  81. /// \return Current time
  82. string
  83. currentTime() {
  84. // Get a text representation of the current time.
  85. time_t curtime;
  86. time(&curtime);
  87. char* buffer = ctime(&curtime);
  88. // Convert to string and strip out the trailing newline
  89. string current_time = buffer;
  90. return isc::util::str::trim(current_time);
  91. }
  92. /// \brief Create Header Sentinel
  93. ///
  94. /// Given the name of a file, create an #ifdef sentinel name. The name is
  95. /// __<name>_<ext>, where <name> is the name of the file, and <ext> is the
  96. /// extension less the leading period. The sentinel will be upper-case.
  97. ///
  98. /// \param file Filename object representing the file.
  99. ///
  100. /// \return Sentinel name
  101. string
  102. sentinel(Filename& file) {
  103. string name = file.name();
  104. string ext = file.extension();
  105. string sentinel_text = "__" + name + "_" + ext.substr(1);
  106. isc::util::str::uppercase(sentinel_text);
  107. return sentinel_text;
  108. }
  109. /// \brief Quote String
  110. ///
  111. /// Inserts an escape character (a backslash) prior to any double quote
  112. /// characters. This is used to handle the fact that the input file does not
  113. /// contain quotes, yet the string will be included in a C++ literal string.
  114. string
  115. quoteString(const string& instring) {
  116. // Create the output string and reserve the space needed to hold the input
  117. // string. (Most input strings will not contain quotes, so this single
  118. // reservation should be all that is needed.)
  119. string outstring;
  120. outstring.reserve(instring.size());
  121. // Iterate through the input string, preceding quotes with a slash.
  122. for (size_t i = 0; i < instring.size(); ++i) {
  123. if (instring[i] == '"') {
  124. outstring += '\\';
  125. }
  126. outstring += instring[i];
  127. }
  128. return outstring;
  129. }
  130. /// \brief Sorted Identifiers
  131. ///
  132. /// Given a dictionary, return a vector holding the message IDs in sorted
  133. /// order.
  134. ///
  135. /// \param dictionary Dictionary to examine
  136. ///
  137. /// \return Sorted list of message IDs
  138. vector<string>
  139. sortedIdentifiers(MessageDictionary& dictionary) {
  140. vector<string> ident;
  141. for (MessageDictionary::const_iterator i = dictionary.begin();
  142. i != dictionary.end(); ++i) {
  143. ident.push_back(i->first);
  144. }
  145. sort(ident.begin(), ident.end());
  146. return ident;
  147. }
  148. /// \brief Split Namespace
  149. ///
  150. /// The $NAMESPACE directive may well specify a namespace in the form a::b.
  151. /// Unfortunately, the C++ "namespace" statement can only accept a single
  152. /// string - to set up the namespace of "a::b" requires two statements, one
  153. /// for "namspace a" and the other for "namespace b".
  154. ///
  155. /// This function returns the set of namespace components as a vector of
  156. /// strings. A vector of one element, containing the empty string, is returned
  157. /// if the anonymous namespace is specified.
  158. ///
  159. /// \param ns Argument to $NAMESPACE (passed by value, as we will be modifying
  160. /// it.)
  161. vector<string>
  162. splitNamespace(string ns) {
  163. // Namespaces components are separated by double colon characters -
  164. // convert to single colons.
  165. size_t dcolon;
  166. while ((dcolon = ns.find("::")) != string::npos) {
  167. ns.replace(dcolon, 2, ":");
  168. }
  169. // ... and return the vector of namespace components split on the single
  170. // colon.
  171. return isc::util::str::tokens(ns, ":");
  172. }
  173. /// \brief Write Opening Namespace(s)
  174. ///
  175. /// Writes the lines listing the namespaces in use.
  176. void
  177. writeOpeningNamespace(ostream& output, const vector<string>& ns) {
  178. if (!ns.empty()) {
  179. // Output namespaces in correct order
  180. for (int i = 0; i < ns.size(); ++i) {
  181. output << "namespace " << ns[i] << " {\n";
  182. }
  183. output << "\n";
  184. }
  185. }
  186. /// \brief Write Closing Namespace(s)
  187. ///
  188. /// Writes the lines listing the namespaces in use.
  189. void
  190. writeClosingNamespace(ostream& output, const vector<string>& ns) {
  191. if (!ns.empty()) {
  192. for (int i = ns.size() - 1; i >= 0; --i) {
  193. output << "} // namespace " << ns[i] << "\n";
  194. }
  195. output << "\n";
  196. }
  197. }
  198. /// \breif Write python file
  199. ///
  200. /// Writes the python file containing the symbol definitions as module level
  201. /// constants. These are objects which register themself at creation time,
  202. /// so they can be replaced by dictionary later.
  203. ///
  204. /// \param file Name of the message file. The source code is written to a file
  205. /// file of the same name but with a .py suffix.
  206. /// \param dictionary The dictionary holding the message definitions.
  207. ///
  208. /// \note We don't use the namespace as in C++. We don't need it, because
  209. /// python file/module works as implicit namespace as well.
  210. void
  211. writePythonFile(const string& file, MessageDictionary& dictionary) {
  212. Filename message_file(file);
  213. Filename python_file(Filename(message_file.name()).useAsDefault(".py"));
  214. // Open the file for writing
  215. ofstream pyfile(python_file.fullName().c_str());
  216. // Write the comment and imports
  217. pyfile <<
  218. "# File created from " << message_file.fullName() << " on " <<
  219. currentTime() << "\n" <<
  220. "\n" <<
  221. "import isc.log\n" <<
  222. "\n";
  223. vector<string> idents(sortedIdentifiers(dictionary));
  224. BOOST_FOREACH(const string& ident, idents) {
  225. pyfile << ident << " = isc.log.create_message(\"" <<
  226. ident << "\", \"" << quoteString(dictionary.getText(ident)) <<
  227. "\")\n";
  228. }
  229. pyfile.close();
  230. }
  231. /// \brief Write Header File
  232. ///
  233. /// Writes the C++ header file containing the symbol definitions. These are
  234. /// "extern" references to definitions in the .cc file. As such, they should
  235. /// take up no space in the module in which they are included, and redundant
  236. /// references should be removed by the compiler.
  237. ///
  238. /// \param file Name of the message file. The header file is written to a
  239. /// file of the same name but with a .h suffix.
  240. /// \param ns Namespace in which the definitions are to be placed. An empty
  241. /// string indicates no namespace.
  242. /// \param dictionary Dictionary holding the message definitions.
  243. void
  244. writeHeaderFile(const string& file, const vector<string>& ns_components,
  245. MessageDictionary& dictionary)
  246. {
  247. Filename message_file(file);
  248. Filename header_file(Filename(message_file.name()).useAsDefault(".h"));
  249. // Text to use as the sentinels.
  250. string sentinel_text = sentinel(header_file);
  251. // Open the output file for writing
  252. ofstream hfile(header_file.fullName().c_str());
  253. if (hfile.fail()) {
  254. throw MessageException(MSG_OPENOUT, header_file.fullName(),
  255. strerror(errno));
  256. }
  257. // Write the header preamble. If there is an error, we'll pick it up
  258. // after the last write.
  259. hfile <<
  260. "// File created from " << message_file.fullName() << " on " <<
  261. currentTime() << "\n" <<
  262. "\n" <<
  263. "#ifndef " << sentinel_text << "\n" <<
  264. "#define " << sentinel_text << "\n" <<
  265. "\n" <<
  266. "#include <log/message_types.h>\n" <<
  267. "\n";
  268. // Write the message identifiers, bounded by a namespace declaration
  269. writeOpeningNamespace(hfile, ns_components);
  270. vector<string> idents = sortedIdentifiers(dictionary);
  271. for (vector<string>::const_iterator j = idents.begin();
  272. j != idents.end(); ++j) {
  273. hfile << "extern const isc::log::MessageID " << *j << ";\n";
  274. }
  275. hfile << "\n";
  276. writeClosingNamespace(hfile, ns_components);
  277. // ... and finally the postamble
  278. hfile << "#endif // " << sentinel_text << "\n";
  279. // Report errors (if any) and exit
  280. if (hfile.fail()) {
  281. throw MessageException(MSG_WRITERR, header_file.fullName(),
  282. strerror(errno));
  283. }
  284. hfile.close();
  285. }
  286. /// \brief Convert Non Alpha-Numeric Characters to Underscores
  287. ///
  288. /// Simple function for use in a call to transform
  289. char
  290. replaceNonAlphaNum(char c) {
  291. return (isalnum(c) ? c : '_');
  292. }
  293. /// \brief Write Program File
  294. ///
  295. /// Writes the C++ source code file. This defines the text of the message
  296. /// symbols, as well as the initializer object that sets the entries in the
  297. /// global dictionary.
  298. ///
  299. /// The construction of the initializer object loads the dictionary with the
  300. /// message text. However, nothing actually references it. If the initializer
  301. /// were in a file by itself, the lack of things referencing it would cause the
  302. /// linker to ignore it when pulling modules out of the logging library in a
  303. /// static link. By including it in the file with the symbol definitions, the
  304. /// module will get included in the link process to resolve the symbol
  305. /// definitions, and so the initializer object will be included in the final
  306. /// image. (Note that there are no such problems when the logging library is
  307. /// built as a dynamically-linked library: the whole library - including the
  308. /// initializer module - gets mapped into address space when the library is
  309. /// loaded, after which all the initializing code (including the constructors
  310. /// of objects declared outside functions) gets run.)
  311. ///
  312. /// There _may_ be a problem when we come to port this to Windows. Microsoft
  313. /// Visual Studio contains a "Whole Program Optimisation" option, where the
  314. /// optimisation is done at link-time, not compiler-time. In this it _may_
  315. /// decide to remove the initializer object because of a lack of references
  316. /// to it. But until BIND-10 is ported to Windows, we won't know.
  317. void
  318. writeProgramFile(const string& file, const vector<string>& ns_components,
  319. MessageDictionary& dictionary)
  320. {
  321. Filename message_file(file);
  322. Filename program_file(Filename(message_file.name()).useAsDefault(".cc"));
  323. // Open the output file for writing
  324. ofstream ccfile(program_file.fullName().c_str());
  325. if (ccfile.fail()) {
  326. throw MessageException(MSG_OPENOUT, program_file.fullName(),
  327. strerror(errno));
  328. }
  329. // Write the preamble. If there is an error, we'll pick it up after
  330. // the last write.
  331. ccfile <<
  332. "// File created from " << message_file.fullName() << " on " <<
  333. currentTime() << "\n" <<
  334. "\n" <<
  335. "#include <cstddef>\n" <<
  336. "#include <log/message_types.h>\n" <<
  337. "#include <log/message_initializer.h>\n" <<
  338. "\n";
  339. // Declare the message symbols themselves.
  340. writeOpeningNamespace(ccfile, ns_components);
  341. vector<string> idents = sortedIdentifiers(dictionary);
  342. for (vector<string>::const_iterator j = idents.begin();
  343. j != idents.end(); ++j) {
  344. ccfile << "extern const isc::log::MessageID " << *j <<
  345. " = \"" << *j << "\";\n";
  346. }
  347. ccfile << "\n";
  348. writeClosingNamespace(ccfile, ns_components);
  349. // Now the code for the message initialization.
  350. ccfile <<
  351. "namespace {\n" <<
  352. "\n" <<
  353. "const char* values[] = {\n";
  354. // Output the identifiers and the associated text.
  355. idents = sortedIdentifiers(dictionary);
  356. for (vector<string>::const_iterator i = idents.begin();
  357. i != idents.end(); ++i) {
  358. ccfile << " \"" << *i << "\", \"" <<
  359. quoteString(dictionary.getText(*i)) << "\",\n";
  360. }
  361. // ... and the postamble
  362. ccfile <<
  363. " NULL\n" <<
  364. "};\n" <<
  365. "\n" <<
  366. "const isc::log::MessageInitializer initializer(values);\n" <<
  367. "\n" <<
  368. "} // Anonymous namespace\n" <<
  369. "\n";
  370. // Report errors (if any) and exit
  371. if (ccfile.fail()) {
  372. throw MessageException(MSG_WRITERR, program_file.fullName(),
  373. strerror(errno));
  374. }
  375. ccfile.close();
  376. }
  377. /// \brief Warn of Duplicate Entries
  378. ///
  379. /// If the input file contained duplicate message IDs, only the first will be
  380. /// processed. However, we should warn about it.
  381. ///
  382. /// \param reader Message Reader used to read the file
  383. void
  384. warnDuplicates(MessageReader& reader) {
  385. // Get the duplicates (the overflow) and, if present, sort them into some
  386. // order and remove those which occur more than once (which mean that they
  387. // occur more than twice in the input file).
  388. MessageReader::MessageIDCollection duplicates = reader.getNotAdded();
  389. if (duplicates.size() > 0) {
  390. cout << "Warning: the following duplicate IDs were found:\n";
  391. sort(duplicates.begin(), duplicates.end());
  392. MessageReader::MessageIDCollection::iterator new_end =
  393. unique(duplicates.begin(), duplicates.end());
  394. for (MessageReader::MessageIDCollection::iterator i = duplicates.begin();
  395. i != new_end; ++i) {
  396. cout << " " << *i << "\n";
  397. }
  398. }
  399. }
  400. /// \brief Main Program
  401. ///
  402. /// Parses the options then dispatches to the appropriate function. See the
  403. /// main file header for the invocation.
  404. int
  405. main(int argc, char* argv[]) {
  406. const char* soptions = "hvp"; // Short options
  407. optind = 1; // Ensure we start a new scan
  408. int opt; // Value of the option
  409. bool doPython = false;
  410. while ((opt = getopt(argc, argv, soptions)) != -1) {
  411. switch (opt) {
  412. case 'p':
  413. doPython = true;
  414. break;
  415. case 'h':
  416. usage();
  417. return 0;
  418. case 'v':
  419. version();
  420. return 0;
  421. default:
  422. // A message will have already been output about the error.
  423. return 1;
  424. }
  425. }
  426. // Do we have the message file?
  427. if (optind < (argc - 1)) {
  428. cout << "Error: excess arguments in command line\n";
  429. usage();
  430. return 1;
  431. } else if (optind >= argc) {
  432. cout << "Error: missing message file\n";
  433. usage();
  434. return 1;
  435. }
  436. string message_file = argv[optind];
  437. try {
  438. // Have identified the file, so process it. First create a local
  439. // dictionary into which the data will be put.
  440. MessageDictionary dictionary;
  441. // Read the data into it.
  442. MessageReader reader(&dictionary);
  443. reader.readFile(message_file);
  444. if (doPython) {
  445. // Warn in case of ignored directives
  446. if (!reader.getNamespace().empty()) {
  447. cerr << "Python mode, ignoring the $NAMESPACE directive" <<
  448. endl;
  449. }
  450. // Write the whole python file
  451. writePythonFile(message_file, dictionary);
  452. } else {
  453. // Get the namespace into which the message definitions will be put and
  454. // split it into components.
  455. vector<string> ns_components =
  456. splitNamespace(reader.getNamespace());
  457. // Write the header file.
  458. writeHeaderFile(message_file, ns_components, dictionary);
  459. // Write the file that defines the message symbols and text
  460. writeProgramFile(message_file, ns_components, dictionary);
  461. }
  462. // Finally, warn of any duplicates encountered.
  463. warnDuplicates(reader);
  464. }
  465. catch (MessageException& e) {
  466. // Create an error message from the ID and the text
  467. MessageDictionary& global = MessageDictionary::globalDictionary();
  468. string text = e.id();
  469. text += ", ";
  470. text += global.getText(e.id());
  471. // Format with arguments
  472. vector<string> args(e.arguments());
  473. for (size_t i(0); i < args.size(); ++ i) {
  474. replacePlaceholder(&text, args[i], i + 1);
  475. }
  476. cerr << text << "\n";
  477. return 1;
  478. }
  479. return 0;
  480. }