loadzone.py.in 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #!@PYTHON@
  2. # Copyright (C) 2012 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. import sys
  17. sys.path.append('@@PYTHONPATH@@')
  18. import time
  19. import signal
  20. from optparse import OptionParser
  21. from isc.dns import *
  22. from isc.datasrc import *
  23. import isc.util.process
  24. import isc.log
  25. from isc.log_messages.loadzone_messages import *
  26. isc.util.process.rename()
  27. # These are needed for logger settings
  28. import bind10_config
  29. import json
  30. from isc.config import module_spec_from_file
  31. from isc.config.ccsession import path_search
  32. isc.log.init("b10-loadzone")
  33. logger = isc.log.Logger("loadzone")
  34. # The default value for the interval of progress report in terms of the
  35. # number of RRs loaded in that interval. Arbitrary choice, but intended to
  36. # be reasonably small to handle emergency exit.
  37. LOAD_INTERVAL_DEFAULT = 10000
  38. class BadArgument(Exception):
  39. '''An exception indicating an error in command line argument.
  40. '''
  41. pass
  42. class LoadFailure(Exception):
  43. '''An exception indicating failure in loading operation.
  44. '''
  45. pass
  46. def set_cmd_options(parser):
  47. '''Helper function to set command-line options.
  48. '''
  49. parser.add_option("-c", "--datasrc-conf", dest="conf", action="store",
  50. help="""configuration of datasrc to load the zone in.
  51. Example: '{"database_file": "/path/to/dbfile/db.sqlite3"}'""",
  52. metavar='CONFIG')
  53. parser.add_option("-d", "--debug", dest="debug_level",
  54. type='int', action="store", default=None,
  55. help="enable debug logs with the specified level [0-99]")
  56. parser.add_option("-i", "--report-interval", dest="report_interval",
  57. type='int', action="store",
  58. default=LOAD_INTERVAL_DEFAULT,
  59. help="""report logs progress per specified number of RRs
  60. (specify 0 to suppress report) [default: %default]""")
  61. parser.add_option("-t", "--datasrc-type", dest="datasrc_type",
  62. action="store", default='sqlite3',
  63. help="""type of data source (e.g., 'sqlite3')\n
  64. [default: %default]""")
  65. parser.add_option("-C", "--class", dest="zone_class", action="store",
  66. default='IN',
  67. help="""RR class of the zone; currently must be 'IN'
  68. [default: %default]""")
  69. class LoadZoneRunner:
  70. '''Main logic for the loadzone.
  71. This is implemented as a class mainly for the convenience of tests.
  72. '''
  73. def __init__(self, command_args):
  74. self.__command_args = command_args
  75. self.__loaded_rrs = 0
  76. self.__interrupted = False # will be set to True on receiving signal
  77. # system-wide log configuration. We need to configure logging this
  78. # way so that the logging policy applies to underlying libraries, too.
  79. self.__log_spec = json.dumps(isc.config.module_spec_from_file(
  80. path_search('logging.spec', bind10_config.PLUGIN_PATHS)).
  81. get_full_spec())
  82. # "severity" and "debuglevel" are the tunable parameters, which will
  83. # be set in _config_log().
  84. self.__log_conf_base = {"loggers":
  85. [{"name": "*",
  86. "output_options":
  87. [{"output": "stderr",
  88. "destination": "console"}]}]}
  89. # These are essentially private, and defined as "protected" for the
  90. # convenience of tests inspecting them
  91. self._zone_class = None
  92. self._zone_name = None
  93. self._zone_file = None
  94. self._datasrc_config = None
  95. self._datasrc_type = None
  96. self._log_severity = 'INFO'
  97. self._log_debuglevel = 0
  98. self._report_interval = LOAD_INTERVAL_DEFAULT
  99. self._config_log()
  100. def _config_log(self):
  101. '''Configure logging policy.
  102. This is essentially private, but defined as "protected" for tests.
  103. '''
  104. self.__log_conf_base['loggers'][0]['severity'] = self._log_severity
  105. self.__log_conf_base['loggers'][0]['debuglevel'] = self._log_debuglevel
  106. isc.log.log_config_update(json.dumps(self.__log_conf_base),
  107. self.__log_spec)
  108. def _parse_args(self):
  109. '''Parse command line options and other arguments.
  110. This is essentially private, but defined as "protected" for tests.
  111. '''
  112. usage_txt = \
  113. 'usage: %prog [options] -c datasrc_config zonename zonefile'
  114. parser = OptionParser(usage=usage_txt)
  115. set_cmd_options(parser)
  116. (options, args) = parser.parse_args(args=self.__command_args)
  117. # Configure logging policy as early as possible
  118. if options.debug_level is not None:
  119. self._log_severity = 'DEBUG'
  120. # optparse performs type check
  121. self._log_debuglevel = int(options.debug_level)
  122. if self._log_debuglevel < 0:
  123. raise BadArgument(
  124. 'Invalid debug level (must be non negative): %d' %
  125. self._log_debuglevel)
  126. self._config_log()
  127. self._datasrc_type = options.datasrc_type
  128. self._datasrc_config = options.conf
  129. if options.conf is None:
  130. self._datasrc_config = self._get_datasrc_config(self._datasrc_type)
  131. try:
  132. self._zone_class = RRClass(options.zone_class)
  133. except isc.dns.InvalidRRClass as ex:
  134. raise BadArgument('Invalid zone class: ' + str(ex))
  135. if self._zone_class != RRClass.IN():
  136. raise BadArgument("RR class is not supported: " +
  137. str(self._zone_class))
  138. self._report_interval = int(options.report_interval)
  139. if self._report_interval < 0:
  140. raise BadArgument(
  141. 'Invalid report interval (must be non negative): %d' %
  142. self._report_interval)
  143. if len(args) != 2:
  144. raise BadArgument('Unexpected number of arguments: %d (must be 2)'
  145. % (len(args)))
  146. try:
  147. self._zone_name = Name(args[0])
  148. except Exception as ex: # too broad, but there's no better granurality
  149. raise BadArgument("Invalid zone name '" + args[0] + "': " +
  150. str(ex))
  151. self._zone_file = args[1]
  152. def _get_datasrc_config(self, datasrc_type):
  153. ''''Return the default data source configuration of given type.
  154. Right now, it only supports SQLite3, and hardcodes the syntax
  155. of the default configuration. It's a kind of workaround to balance
  156. convenience of users and minimizing hardcoding of data source
  157. specific logic in the entire tool. In future this should be
  158. more sophisticated.
  159. This is essentially a private helper method for _parse_arg(),
  160. but defined as "protected" so tests can use it directly.
  161. '''
  162. if datasrc_type != 'sqlite3':
  163. raise BadArgument('default config is not available for ' +
  164. datasrc_type)
  165. default_db_file = bind10_config.DATA_PATH + '/zone.sqlite3'
  166. logger.info(LOADZONE_SQLITE3_USING_DEFAULT_CONFIG, default_db_file)
  167. return '{"database_file": "' + default_db_file + '"}'
  168. def _report_progress(self, loaded_rrs):
  169. '''Dump the current progress report to stdout.
  170. This is essentially private, but defined as "protected" for tests.
  171. '''
  172. elapsed = time.time() - self.__start_time
  173. sys.stdout.write("\r" + (80 * " "))
  174. sys.stdout.write("\r%d RRs loaded in %.2f seconds" %
  175. (loaded_rrs, elapsed))
  176. def _do_load(self):
  177. '''Main part of the load logic.
  178. This is essentially private, but defined as "protected" for tests.
  179. '''
  180. created = False
  181. try:
  182. datasrc_client = DataSourceClient(self._datasrc_type,
  183. self._datasrc_config)
  184. created = datasrc_client.create_zone(self._zone_name)
  185. if created:
  186. logger.info(LOADZONE_ZONE_CREATED, self._zone_name,
  187. self._zone_class)
  188. else:
  189. logger.info(LOADZONE_ZONE_UPDATING, self._zone_name,
  190. self._zone_class)
  191. loader = ZoneLoader(datasrc_client, self._zone_name,
  192. self._zone_file)
  193. self.__start_time = time.time()
  194. if self._report_interval > 0:
  195. limit = self._report_interval
  196. else:
  197. # Even if progress report is suppressed, we still load
  198. # incrementally so we won't delay catching signals too long.
  199. limit = LOAD_INTERVAL_DEFAULT
  200. while (not self.__interrupted and
  201. not loader.load_incremental(limit)):
  202. self.__loaded_rrs += self._report_interval
  203. if self._report_interval > 0:
  204. self._report_progress(self.__loaded_rrs)
  205. if self.__interrupted:
  206. raise LoadFailure('loading interrupted by signal')
  207. # On successful completion, add final '\n' to the progress
  208. # report output (on failure don't bother to make it prettier).
  209. if (self._report_interval > 0 and
  210. self.__loaded_rrs >= self._report_interval):
  211. sys.stdout.write('\n')
  212. except Exception as ex:
  213. # release any remaining lock held in the loader
  214. loader = None
  215. if created:
  216. datasrc_client.delete_zone(self._zone_name)
  217. logger.error(LOADZONE_CANCEL_CREATE_ZONE, self._zone_name,
  218. self._zone_class)
  219. raise LoadFailure(str(ex))
  220. def _set_signal_handlers(self):
  221. signal.signal(signal.SIGINT, self._interrupt_handler)
  222. signal.signal(signal.SIGTERM, self._interrupt_handler)
  223. def _interrupt_handler(self, signal, frame):
  224. self.__interrupted = True
  225. def run(self):
  226. '''Top-level method, simply calling other helpers'''
  227. try:
  228. self._set_signal_handlers()
  229. self._parse_args()
  230. self._do_load()
  231. total_elapsed_txt = "%.2f" % (time.time() - self.__start_time)
  232. logger.info(LOADZONE_DONE, self.__loaded_rrs, self._zone_name,
  233. self._zone_class, total_elapsed_txt)
  234. return 0
  235. except BadArgument as ex:
  236. logger.error(LOADZONE_ARGUMENT_ERROR, ex)
  237. except LoadFailure as ex:
  238. logger.error(LOADZONE_LOAD_ERROR, self._zone_name,
  239. self._zone_class, ex)
  240. except Exception as ex:
  241. logger.error(LOADZONE_UNEXPECTED_FAILURE, ex)
  242. return 1
  243. if '__main__' == __name__:
  244. runner = LoadZoneRunner(sys.argv[1:])
  245. ret = runner.run()
  246. sys.exit(ret)
  247. ## Local Variables:
  248. ## mode: python
  249. ## End: