loadzone.py.in 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. from datetime import timedelta
  27. isc.util.process.rename()
  28. # These are needed for logger settings
  29. import bind10_config
  30. import json
  31. from isc.config import module_spec_from_file
  32. from isc.config.ccsession import path_search
  33. isc.log.init("b10-loadzone")
  34. logger = isc.log.Logger("loadzone")
  35. # The default value for the interval of progress report in terms of the
  36. # number of RRs loaded in that interval. Arbitrary choice, but intended to
  37. # be reasonably small to handle emergency exit.
  38. LOAD_INTERVAL_DEFAULT = 10000
  39. class BadArgument(Exception):
  40. '''An exception indicating an error in command line argument.
  41. '''
  42. pass
  43. class LoadFailure(Exception):
  44. '''An exception indicating failure in loading operation.
  45. '''
  46. pass
  47. def set_cmd_options(parser):
  48. '''Helper function to set command-line options.
  49. '''
  50. parser.add_option("-c", "--datasrc-conf", dest="conf", action="store",
  51. help="""configuration of datasrc to load the zone in.
  52. Example: '{"database_file": "/path/to/dbfile/db.sqlite3"}'""",
  53. metavar='CONFIG')
  54. parser.add_option("-d", "--debug", dest="debug_level",
  55. type='int', action="store", default=None,
  56. help="enable debug logs with the specified level [0-99]")
  57. parser.add_option("-i", "--report-interval", dest="report_interval",
  58. type='int', action="store",
  59. default=LOAD_INTERVAL_DEFAULT,
  60. help="""report logs progress per specified number of RRs
  61. (specify 0 to suppress report) [default: %default]""")
  62. parser.add_option("-t", "--datasrc-type", dest="datasrc_type",
  63. action="store", default='sqlite3',
  64. help="""type of data source (e.g., 'sqlite3')\n
  65. [default: %default]""")
  66. parser.add_option("-C", "--class", dest="zone_class", action="store",
  67. default='IN',
  68. help="""RR class of the zone; currently must be 'IN'
  69. [default: %default]""")
  70. class LoadZoneRunner:
  71. '''Main logic for the loadzone.
  72. This is implemented as a class mainly for the convenience of tests.
  73. '''
  74. def __init__(self, command_args):
  75. self.__command_args = command_args
  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, but defined as "protected" for the
  90. # convenience of tests inspecting them
  91. self._loaded_rrs = 0
  92. self._zone_class = None
  93. self._zone_name = None
  94. self._zone_file = None
  95. self._datasrc_config = None
  96. self._datasrc_type = None
  97. self._log_severity = 'INFO'
  98. self._log_debuglevel = 0
  99. self._report_interval = LOAD_INTERVAL_DEFAULT
  100. self._start_time = None
  101. # This one will be used in (rare) cases where we want to allow tests to
  102. # fake time.time()
  103. self._get_time = time.time
  104. self._config_log()
  105. def _config_log(self):
  106. '''Configure logging policy.
  107. This is essentially private, but defined as "protected" for tests.
  108. '''
  109. self.__log_conf_base['loggers'][0]['severity'] = self._log_severity
  110. self.__log_conf_base['loggers'][0]['debuglevel'] = self._log_debuglevel
  111. isc.log.log_config_update(json.dumps(self.__log_conf_base),
  112. self.__log_spec)
  113. def _parse_args(self):
  114. '''Parse command line options and other arguments.
  115. This is essentially private, but defined as "protected" for tests.
  116. '''
  117. usage_txt = \
  118. 'usage: %prog [options] -c datasrc_config zonename zonefile'
  119. parser = OptionParser(usage=usage_txt)
  120. set_cmd_options(parser)
  121. (options, args) = parser.parse_args(args=self.__command_args)
  122. # Configure logging policy as early as possible
  123. if options.debug_level is not None:
  124. self._log_severity = 'DEBUG'
  125. # optparse performs type check
  126. self._log_debuglevel = int(options.debug_level)
  127. if self._log_debuglevel < 0:
  128. raise BadArgument(
  129. 'Invalid debug level (must be non negative): %d' %
  130. self._log_debuglevel)
  131. self._config_log()
  132. self._datasrc_type = options.datasrc_type
  133. self._datasrc_config = options.conf
  134. if options.conf is None:
  135. self._datasrc_config = self._get_datasrc_config(self._datasrc_type)
  136. try:
  137. self._zone_class = RRClass(options.zone_class)
  138. except isc.dns.InvalidRRClass as ex:
  139. raise BadArgument('Invalid zone class: ' + str(ex))
  140. if self._zone_class != RRClass.IN():
  141. raise BadArgument("RR class is not supported: " +
  142. str(self._zone_class))
  143. self._report_interval = int(options.report_interval)
  144. if self._report_interval < 0:
  145. raise BadArgument(
  146. 'Invalid report interval (must be non negative): %d' %
  147. self._report_interval)
  148. if len(args) != 2:
  149. raise BadArgument('Unexpected number of arguments: %d (must be 2)'
  150. % (len(args)))
  151. try:
  152. self._zone_name = Name(args[0])
  153. except Exception as ex: # too broad, but there's no better granurality
  154. raise BadArgument("Invalid zone name '" + args[0] + "': " +
  155. str(ex))
  156. self._zone_file = args[1]
  157. def _get_datasrc_config(self, datasrc_type):
  158. ''''Return the default data source configuration of given type.
  159. Right now, it only supports SQLite3, and hardcodes the syntax
  160. of the default configuration. It's a kind of workaround to balance
  161. convenience of users and minimizing hardcoding of data source
  162. specific logic in the entire tool. In future this should be
  163. more sophisticated.
  164. This is essentially a private helper method for _parse_arg(),
  165. but defined as "protected" so tests can use it directly.
  166. '''
  167. if datasrc_type != 'sqlite3':
  168. raise BadArgument('default config is not available for ' +
  169. datasrc_type)
  170. default_db_file = bind10_config.DATA_PATH + '/zone.sqlite3'
  171. logger.info(LOADZONE_SQLITE3_USING_DEFAULT_CONFIG, default_db_file)
  172. return '{"database_file": "' + default_db_file + '"}'
  173. def _report_progress(self, loaded_rrs, progress, dump=True):
  174. '''Dump the current progress report to stdout.
  175. This is essentially private, but defined as "protected" for tests.
  176. Normally dump is True, but tests will set it False to get the
  177. text to be reported. Tests may also fake self._get_time (which
  178. is set to time.time() by default) and self._start_time for control
  179. time related conditions.
  180. '''
  181. elapsed = self._get_time() - self._start_time
  182. speed = int(loaded_rrs / elapsed) if elapsed > 0 else 0
  183. etc = None # calculate estimated time of completion
  184. if progress != ZoneLoader.PROGRESS_UNKNOWN:
  185. etc = (1 - progress) * (elapsed / progress)
  186. # Build report text
  187. report_txt = '\r%d RRs' % loaded_rrs
  188. if progress != ZoneLoader.PROGRESS_UNKNOWN:
  189. report_txt += ' (%.1f%%)' % (progress * 100)
  190. report_txt += ' in %s, %d RRs/sec' % \
  191. (str(timedelta(seconds=int(elapsed))), speed)
  192. if etc is not None:
  193. report_txt += ', %s ETC' % str(timedelta(seconds=int(etc)))
  194. # Dump or return the report text.
  195. if dump:
  196. sys.stdout.write("\r" + (80 * " "))
  197. sys.stdout.write(report_txt)
  198. else:
  199. return report_txt
  200. def _do_load(self):
  201. '''Main part of the load logic.
  202. This is essentially private, but defined as "protected" for tests.
  203. '''
  204. created = False
  205. try:
  206. datasrc_client = DataSourceClient(self._datasrc_type,
  207. self._datasrc_config)
  208. created = datasrc_client.create_zone(self._zone_name)
  209. if created:
  210. logger.info(LOADZONE_ZONE_CREATED, self._zone_name,
  211. self._zone_class)
  212. else:
  213. logger.info(LOADZONE_ZONE_UPDATING, self._zone_name,
  214. self._zone_class)
  215. loader = ZoneLoader(datasrc_client, self._zone_name,
  216. self._zone_file)
  217. self._start_time = time.time()
  218. if self._report_interval > 0:
  219. limit = self._report_interval
  220. else:
  221. # Even if progress report is suppressed, we still load
  222. # incrementally so we won't delay catching signals too long.
  223. limit = LOAD_INTERVAL_DEFAULT
  224. while (not self.__interrupted and
  225. not loader.load_incremental(limit)):
  226. self._loaded_rrs += self._report_interval
  227. if self._report_interval > 0:
  228. self._report_progress(self._loaded_rrs,
  229. loader.get_progress())
  230. if self.__interrupted:
  231. raise LoadFailure('loading interrupted by signal')
  232. # On successful completion, add final '\n' to the progress
  233. # report output (on failure don't bother to make it prettier).
  234. if (self._report_interval > 0 and
  235. self._loaded_rrs >= self._report_interval):
  236. sys.stdout.write('\n')
  237. # record the final count of the loaded RRs for logging
  238. self._loaded_rrs = loader.get_rr_count()
  239. except Exception as ex:
  240. # release any remaining lock held in the loader
  241. loader = None
  242. if created:
  243. datasrc_client.delete_zone(self._zone_name)
  244. logger.error(LOADZONE_CANCEL_CREATE_ZONE, self._zone_name,
  245. self._zone_class)
  246. raise LoadFailure(str(ex))
  247. def _set_signal_handlers(self):
  248. signal.signal(signal.SIGINT, self._interrupt_handler)
  249. signal.signal(signal.SIGTERM, self._interrupt_handler)
  250. def _interrupt_handler(self, signal, frame):
  251. self.__interrupted = True
  252. def run(self):
  253. '''Top-level method, simply calling other helpers'''
  254. try:
  255. self._set_signal_handlers()
  256. self._parse_args()
  257. self._do_load()
  258. total_elapsed_txt = "%.2f" % (time.time() - self._start_time)
  259. logger.info(LOADZONE_DONE, self._loaded_rrs, self._zone_name,
  260. self._zone_class, total_elapsed_txt)
  261. return 0
  262. except BadArgument as ex:
  263. logger.error(LOADZONE_ARGUMENT_ERROR, ex)
  264. except LoadFailure as ex:
  265. logger.error(LOADZONE_LOAD_ERROR, self._zone_name,
  266. self._zone_class, ex)
  267. except Exception as ex:
  268. logger.error(LOADZONE_UNEXPECTED_FAILURE, ex)
  269. return 1
  270. if '__main__' == __name__:
  271. runner = LoadZoneRunner(sys.argv[1:])
  272. ret = runner.run()
  273. sys.exit(ret)
  274. ## Local Variables:
  275. ## mode: python
  276. ## End: