stats_httpd.py.in 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #!@PYTHON@
  2. # Copyright (C) 2011-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. """
  17. A standalone HTTP server for HTTP/XML interface of statistics in BIND 10
  18. """
  19. import sys; sys.path.append ('@@PYTHONPATH@@')
  20. import os
  21. import time
  22. import errno
  23. import select
  24. from optparse import OptionParser, OptionValueError
  25. import http.server
  26. import socket
  27. import string
  28. import xml.etree.ElementTree
  29. import urllib.parse
  30. import re
  31. import isc.cc
  32. import isc.config
  33. import isc.util.process
  34. import isc.log
  35. from isc.log_messages.stats_httpd_messages import *
  36. isc.log.init("b10-stats-httpd")
  37. logger = isc.log.Logger("stats-httpd")
  38. # Some constants for debug levels.
  39. DBG_STATHTTPD_INIT = logger.DBGLVL_START_SHUT
  40. DBG_STATHTTPD_MESSAGING = logger.DBGLVL_COMMAND
  41. # If B10_FROM_SOURCE is set in the environment, we use data files
  42. # from a directory relative to that, otherwise we use the ones
  43. # installed on the system
  44. if "B10_FROM_SOURCE" in os.environ:
  45. BASE_LOCATION = os.environ["B10_FROM_SOURCE"] + os.sep + \
  46. "src" + os.sep + "bin" + os.sep + "stats"
  47. else:
  48. PREFIX = "@prefix@"
  49. DATAROOTDIR = "@datarootdir@"
  50. BASE_LOCATION = "@datadir@" + os.sep + "@PACKAGE@"
  51. BASE_LOCATION = BASE_LOCATION.replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  52. SPECFILE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd.spec"
  53. XML_TEMPLATE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd-xml.tpl"
  54. XSD_TEMPLATE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd-xsd.tpl"
  55. XSL_TEMPLATE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd-xsl.tpl"
  56. # These variables are paths part of URL.
  57. # eg. "http://${address}" + XXX_URL_PATH
  58. XML_URL_PATH = '/bind10/statistics/xml'
  59. XSD_URL_PATH = '/bind10/statistics.xsd'
  60. XSL_URL_PATH = '/bind10/statistics.xsl'
  61. # TODO: This should be considered later.
  62. XSD_NAMESPACE = 'http://bind10.isc.org/bind10'
  63. XMLNS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
  64. # constant parameter of XML
  65. XML_ROOT_ELEMENT = 'bind10:statistics'
  66. XML_ROOT_ATTRIB = { 'xsi:schemaLocation' : '%s %s' % (XSD_NAMESPACE, XSD_URL_PATH),
  67. 'xmlns:bind10' : XSD_NAMESPACE,
  68. 'xmlns:xsi' : XMLNS_XSI }
  69. # Assign this process name
  70. isc.util.process.rename()
  71. def item_name_list(element, identifier):
  72. """Returns list of items. The first argument elemet is dict-type
  73. value to traverse, the second argument is a string separated
  74. '/'. This is a start porint to traverse. At the end in the
  75. method. The list to be returned is sorted. """
  76. elem = isc.cc.data.find(element, identifier)
  77. ret = []
  78. ident = ''
  79. if identifier and len(str(identifier)) > 0:
  80. ident = str(identifier)
  81. ret.append(ident)
  82. if type(elem) is dict:
  83. if len(ident) > 0:
  84. ident = '%s/' % ident
  85. for (key, value) in elem.items():
  86. idstr = '%s%s' % (ident, key)
  87. ret += item_name_list(element, idstr)
  88. elif type(elem) is list:
  89. for i in range(0, len(elem)):
  90. idstr = '%s[%s]' % (ident, i)
  91. ret += item_name_list(element, idstr)
  92. ret.sort()
  93. return ret
  94. class HttpHandler(http.server.BaseHTTPRequestHandler):
  95. """HTTP handler class for HttpServer class. The class inhrits the super
  96. class http.server.BaseHTTPRequestHandler. It implemets do_GET()
  97. and do_HEAD() and orverrides log_message()"""
  98. def do_GET(self):
  99. body = self.send_head()
  100. if body is not None:
  101. self.wfile.write(body.encode())
  102. def do_HEAD(self):
  103. self.send_head()
  104. def send_head(self):
  105. try:
  106. req_path = self.path
  107. req_path = urllib.parse.urlsplit(req_path).path
  108. req_path = urllib.parse.unquote(req_path)
  109. body = None
  110. if req_path.find('%s/' % XML_URL_PATH) == 0:
  111. req_path = os.path.normpath(req_path)
  112. req_path = req_path.lstrip('%s/' % XML_URL_PATH)
  113. path_dirs = req_path.split('/')
  114. path_dirs = [ d for d in filter(None, path_dirs) ]
  115. req_path = '/'.join(path_dirs)
  116. body = self.server.xml_handler(req_path)
  117. elif req_path == XSD_URL_PATH:
  118. body = self.server.xsd_handler()
  119. elif req_path == XSL_URL_PATH:
  120. body = self.server.xsl_handler()
  121. else:
  122. if 'Host' in self.headers.keys() and \
  123. ( req_path == '/' or req_path == XML_URL_PATH ):
  124. # redirect to XML URL only when requested with '/' or XML_URL_PATH
  125. toloc = "http://%s%s/" % (self.headers.get('Host'), XML_URL_PATH)
  126. self.send_response(302)
  127. self.send_header("Location", toloc)
  128. self.end_headers()
  129. return None
  130. else:
  131. # Couldn't find HOST
  132. self.send_error(404)
  133. return None
  134. except StatsHttpdDataError as err:
  135. # Couldn't find neither specified module name nor
  136. # specified item name
  137. self.send_error(404)
  138. logger.error(STATHTTPD_SERVER_DATAERROR, err)
  139. return None
  140. except StatsHttpdError as err:
  141. self.send_error(500)
  142. logger.error(STATHTTPD_SERVER_ERROR, err)
  143. return None
  144. else:
  145. self.send_response(200)
  146. self.send_header("Content-type", "text/xml")
  147. self.send_header("Content-Length", len(body))
  148. self.end_headers()
  149. return body
  150. class HttpServerError(Exception):
  151. """Exception class for HttpServer class. It is intended to be
  152. passed from the HttpServer object to the StatsHttpd object."""
  153. pass
  154. class HttpServer(http.server.HTTPServer):
  155. """HTTP Server class. The class inherits the super
  156. http.server.HTTPServer. Some parameters are specified as
  157. arguments, which are xml_handler, xsd_handler, xsl_handler, and
  158. log_writer. These all are parameters which the StatsHttpd object
  159. has. The handler parameters are references of functions which
  160. return body of each document. The last parameter log_writer is
  161. reference of writer function to just write to
  162. sys.stderr.write. They are intended to be referred by HttpHandler
  163. object."""
  164. def __init__(self, server_address, handler,
  165. xml_handler, xsd_handler, xsl_handler, log_writer):
  166. self.server_address = server_address
  167. self.xml_handler = xml_handler
  168. self.xsd_handler = xsd_handler
  169. self.xsl_handler = xsl_handler
  170. self.log_writer = log_writer
  171. http.server.HTTPServer.__init__(self, server_address, handler)
  172. class StatsHttpdError(Exception):
  173. """Exception class for StatsHttpd class. It is intended to be
  174. thrown from the the StatsHttpd object to the HttpHandler object or
  175. main routine."""
  176. pass
  177. class StatsHttpdDataError(Exception):
  178. """Exception class for StatsHttpd class. The reason seems to be
  179. due to the data. It is intended to be thrown from the the
  180. StatsHttpd object to the HttpHandler object or main routine."""
  181. pass
  182. class StatsHttpd:
  183. """The main class of HTTP server of HTTP/XML interface for
  184. statistics module. It handles HTTP requests, and command channel
  185. and config channel CC session. It uses select.select function
  186. while waiting for clients requests."""
  187. def __init__(self):
  188. self.running = False
  189. self.poll_intval = 0.5
  190. self.write_log = sys.stderr.write
  191. self.mccs = None
  192. self.httpd = []
  193. self.open_mccs()
  194. self.config = {}
  195. self.load_config()
  196. self.http_addrs = []
  197. self.mccs.start()
  198. try:
  199. self.open_httpd()
  200. except HttpServerError:
  201. # if some exception, e.g. address in use, is raised, then it closes mccs and httpd
  202. self.close_mccs()
  203. raise
  204. def open_mccs(self):
  205. """Opens a ModuleCCSession object"""
  206. # create ModuleCCSession
  207. logger.debug(DBG_STATHTTPD_INIT, STATHTTPD_STARTING_CC_SESSION)
  208. self.mccs = isc.config.ModuleCCSession(
  209. SPECFILE_LOCATION, self.config_handler, self.command_handler)
  210. self.cc_session = self.mccs._session
  211. def close_mccs(self):
  212. """Closes a ModuleCCSession object"""
  213. if self.mccs is None:
  214. return
  215. self.mccs.send_stopping()
  216. logger.debug(DBG_STATHTTPD_INIT, STATHTTPD_CLOSING_CC_SESSION)
  217. self.mccs.close()
  218. self.mccs = None
  219. def load_config(self, new_config={}):
  220. """Loads configuration from spec file or new configuration
  221. from the config manager"""
  222. # load config
  223. if len(self.config) == 0:
  224. self.config = dict([
  225. (itm['item_name'], self.mccs.get_value(itm['item_name'])[0])
  226. for itm in self.mccs.get_module_spec().get_config_spec()
  227. ])
  228. self.config.update(new_config)
  229. # set addresses and ports for HTTP
  230. addrs = []
  231. if 'listen_on' in self.config:
  232. for cf in self.config['listen_on']:
  233. if 'address' in cf and 'port' in cf:
  234. addrs.append((cf['address'], cf['port']))
  235. self.http_addrs = addrs
  236. def open_httpd(self):
  237. """Opens sockets for HTTP. Iterating each HTTP address to be
  238. configured in spec file"""
  239. for addr in self.http_addrs:
  240. self.httpd.append(self._open_httpd(addr))
  241. def _open_httpd(self, server_address):
  242. httpd = None
  243. try:
  244. # get address family for the server_address before
  245. # creating HttpServer object. If a specified address is
  246. # not numerical, gaierror may be thrown.
  247. address_family = socket.getaddrinfo(
  248. server_address[0], server_address[1], 0,
  249. socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_NUMERICHOST
  250. )[0][0]
  251. HttpServer.address_family = address_family
  252. httpd = HttpServer(
  253. server_address, HttpHandler,
  254. self.xml_handler, self.xsd_handler, self.xsl_handler,
  255. self.write_log)
  256. logger.info(STATHTTPD_STARTED, server_address[0],
  257. server_address[1])
  258. return httpd
  259. except (socket.gaierror, socket.error,
  260. OverflowError, TypeError) as err:
  261. if httpd:
  262. httpd.server_close()
  263. raise HttpServerError(
  264. "Invalid address %s, port %s: %s: %s" %
  265. (server_address[0], server_address[1],
  266. err.__class__.__name__, err))
  267. def close_httpd(self):
  268. """Closes sockets for HTTP"""
  269. while len(self.httpd)>0:
  270. ht = self.httpd.pop()
  271. logger.info(STATHTTPD_CLOSING, ht.server_address[0],
  272. ht.server_address[1])
  273. ht.server_close()
  274. def start(self):
  275. """Starts StatsHttpd objects to run. Waiting for client
  276. requests by using select.select functions"""
  277. self.running = True
  278. while self.running:
  279. try:
  280. (rfd, wfd, xfd) = select.select(
  281. self.get_sockets(), [], [], self.poll_intval)
  282. except select.error as err:
  283. # select.error exception is caught only in the case of
  284. # EINTR, or in other cases it is just thrown.
  285. if err.args[0] == errno.EINTR:
  286. (rfd, wfd, xfd) = ([], [], [])
  287. else:
  288. raise
  289. # FIXME: This module can handle only one request at a
  290. # time. If someone sends only part of the request, we block
  291. # waiting for it until we time out.
  292. # But it isn't so big issue for administration purposes.
  293. for fd in rfd + xfd:
  294. if fd == self.mccs.get_socket():
  295. self.mccs.check_command(nonblock=False)
  296. continue
  297. for ht in self.httpd:
  298. if fd == ht.socket:
  299. ht.handle_request()
  300. break
  301. self.stop()
  302. def stop(self):
  303. """Stops the running StatsHttpd objects. Closes CC session and
  304. HTTP handling sockets"""
  305. logger.info(STATHTTPD_SHUTDOWN)
  306. self.close_httpd()
  307. self.close_mccs()
  308. self.running = False
  309. def get_sockets(self):
  310. """Returns sockets to select.select"""
  311. sockets = []
  312. if self.mccs is not None:
  313. sockets.append(self.mccs.get_socket())
  314. if len(self.httpd) > 0:
  315. for ht in self.httpd:
  316. sockets.append(ht.socket)
  317. return sockets
  318. def config_handler(self, new_config):
  319. """Config handler for the ModuleCCSession object. It resets
  320. addresses and ports to listen HTTP requests on."""
  321. logger.debug(DBG_STATHTTPD_MESSAGING, STATHTTPD_HANDLE_CONFIG,
  322. new_config)
  323. errors = []
  324. if not self.mccs.get_module_spec().\
  325. validate_config(False, new_config, errors):
  326. return isc.config.ccsession.create_answer(
  327. 1, ", ".join(errors))
  328. # backup old config
  329. old_config = self.config.copy()
  330. self.load_config(new_config)
  331. # If the http sockets aren't opened or
  332. # if new_config doesn't have'listen_on', it returns
  333. if len(self.httpd) == 0 or 'listen_on' not in new_config:
  334. return isc.config.ccsession.create_answer(0)
  335. self.close_httpd()
  336. try:
  337. self.open_httpd()
  338. except HttpServerError as err:
  339. logger.error(STATHTTPD_SERVER_ERROR, err)
  340. # restore old config
  341. self.load_config(old_config)
  342. self.open_httpd()
  343. return isc.config.ccsession.create_answer(1, str(err))
  344. else:
  345. return isc.config.ccsession.create_answer(0)
  346. def command_handler(self, command, args):
  347. """Command handler for the ModuleCCSesson object. It handles
  348. "status" and "shutdown" commands."""
  349. if command == "status":
  350. logger.debug(DBG_STATHTTPD_MESSAGING,
  351. STATHTTPD_RECEIVED_STATUS_COMMAND)
  352. return isc.config.ccsession.create_answer(
  353. 0, "Stats Httpd is up. (PID " + str(os.getpid()) + ")")
  354. elif command == "shutdown":
  355. logger.debug(DBG_STATHTTPD_MESSAGING,
  356. STATHTTPD_RECEIVED_SHUTDOWN_COMMAND)
  357. self.running = False
  358. return isc.config.ccsession.create_answer(0)
  359. else:
  360. logger.debug(DBG_STATHTTPD_MESSAGING,
  361. STATHTTPD_RECEIVED_UNKNOWN_COMMAND, command)
  362. return isc.config.ccsession.create_answer(
  363. 1, "Unknown command: " + str(command))
  364. def get_stats_data(self, owner=None, name=None):
  365. """Requests statistics data to the Stats daemon and returns
  366. the data which obtains from it. The first argument is the
  367. module name which owns the statistics data, the second
  368. argument is one name of the statistics items which the the
  369. module owns. The second argument cannot be specified when the
  370. first argument is not specified. It returns the statistics
  371. data of the specified module or item. When the session timeout
  372. or the session error is occurred, it raises
  373. StatsHttpdError. When the stats daemon returns none-zero
  374. value, it raises StatsHttpdDataError."""
  375. param = {}
  376. if owner is None and name is None:
  377. param = None
  378. if owner is not None:
  379. param['owner'] = owner
  380. if name is not None:
  381. param['name'] = name
  382. try:
  383. seq = self.cc_session.group_sendmsg(
  384. isc.config.ccsession.create_command('show', param), 'Stats')
  385. (answer, env) = self.cc_session.group_recvmsg(False, seq)
  386. if answer:
  387. (rcode, value) = isc.config.ccsession.parse_answer(answer)
  388. except (isc.cc.session.SessionTimeout,
  389. isc.cc.session.SessionError) as err:
  390. raise StatsHttpdError("%s: %s" %
  391. (err.__class__.__name__, err))
  392. else:
  393. if rcode == 0:
  394. return value
  395. else:
  396. raise StatsHttpdDataError("Stats module: %s" % str(value))
  397. def get_stats_spec(self, owner=None, name=None):
  398. """Requests statistics data to the Stats daemon and returns
  399. the data which obtains from it. The first argument is the
  400. module name which owns the statistics data, the second
  401. argument is one name of the statistics items which the the
  402. module owns. The second argument cannot be specified when the
  403. first argument is not specified. It returns the statistics
  404. specification of the specified module or item. When the
  405. session timeout or the session error is occurred, it raises
  406. StatsHttpdError. When the stats daemon returns none-zero
  407. value, it raises StatsHttpdDataError."""
  408. param = {}
  409. if owner is None and name is None:
  410. param = None
  411. if owner is not None:
  412. param['owner'] = owner
  413. if name is not None:
  414. param['name'] = name
  415. try:
  416. seq = self.cc_session.group_sendmsg(
  417. isc.config.ccsession.create_command('showschema', param), 'Stats')
  418. (answer, env) = self.cc_session.group_recvmsg(False, seq)
  419. if answer:
  420. (rcode, value) = isc.config.ccsession.parse_answer(answer)
  421. if rcode == 0:
  422. return value
  423. else:
  424. raise StatsHttpdDataError("Stats module: %s" % str(value))
  425. except (isc.cc.session.SessionTimeout,
  426. isc.cc.session.SessionError) as err:
  427. raise StatsHttpdError("%s: %s" %
  428. (err.__class__.__name__, err))
  429. def xml_handler(self, path=''):
  430. """Requests the specified statistics data and specification by
  431. using the functions get_stats_data and get_stats_spec
  432. respectively and loads the XML template file and returns the
  433. string of the XML document.The argument is a path in the
  434. requested URI."""
  435. dirs = [ d for d in path.split("/") if len(d) > 0 ]
  436. module_name = None
  437. item_name = None
  438. if len(dirs) > 0:
  439. module_name = dirs[0]
  440. if len(dirs) > 1:
  441. item_name = dirs[1]
  442. # removed an index string when list-type value is
  443. # requested. Because such a item name can be accept by the
  444. # stats module currently.
  445. item_name = re.sub('\[\d+\]$', '', item_name)
  446. stats_spec = self.get_stats_spec(module_name, item_name)
  447. stats_data = self.get_stats_data(module_name, item_name)
  448. path_list = []
  449. try:
  450. path_list = item_name_list(stats_data, path)
  451. except isc.cc.data.DataNotFoundError as err:
  452. raise StatsHttpdDataError(
  453. "%s: %s" % (err.__class__.__name__, err))
  454. item_list = []
  455. for path in path_list:
  456. dirs = path.split("/")
  457. if len(dirs) < 2: continue
  458. item = {}
  459. item['identifier'] = path
  460. value = isc.cc.data.find(stats_data, path)
  461. if type(value) is bool:
  462. value = str(value).lower()
  463. if type(value) is dict or type(value) is list:
  464. value = None
  465. if value is not None:
  466. item['value'] = str(value)
  467. owner = dirs[0]
  468. item['owner'] = owner
  469. item['uri'] = urllib.parse.quote('%s/%s' % (XML_URL_PATH, path))
  470. item_path = '/'.join(dirs[1:])
  471. spec = isc.config.find_spec_part(stats_spec[owner], item_path)
  472. for key in ['name', 'type', 'description', 'title', \
  473. 'optional', 'default', 'format']:
  474. value = spec.get('item_%s' % key)
  475. if type(value) is bool:
  476. value = str(value).lower()
  477. if type(value) is dict or type(value) is list:
  478. value = None
  479. if value is not None:
  480. item[key] = str(value)
  481. item_list.append(item)
  482. xml_elem = xml.etree.ElementTree.Element(
  483. XML_ROOT_ELEMENT, attrib=XML_ROOT_ATTRIB)
  484. for item in item_list:
  485. item_elem = xml.etree.ElementTree.Element('item', attrib=item)
  486. xml_elem.append(item_elem)
  487. # The coding conversion is tricky. xml..tostring() of Python 3.2
  488. # returns bytes (not string) regardless of the coding, while
  489. # tostring() of Python 3.1 returns a string. To support both
  490. # cases transparently, we first make sure tostring() returns
  491. # bytes by specifying utf-8 and then convert the result to a
  492. # plain string (code below assume it).
  493. # FIXME: Non-ASCII characters might be lost here. Consider how
  494. # the whole system should handle non-ASCII characters.
  495. xml_string = str(xml.etree.ElementTree.tostring(xml_elem, encoding='utf-8'),
  496. encoding='us-ascii')
  497. self.xml_body = self.open_template(XML_TEMPLATE_LOCATION).substitute(
  498. xml_string=xml_string, xsl_url_path=XSL_URL_PATH)
  499. return self.xml_body
  500. def xsd_handler(self):
  501. """Loads the XSD template file, replaces the variable strings,
  502. and returns the string of the XSD document."""
  503. self.xsd_body = self.open_template(XSD_TEMPLATE_LOCATION).substitute(
  504. xsd_namespace=XSD_NAMESPACE)
  505. return self.xsd_body
  506. def xsl_handler(self, module_name=None, item_name=None):
  507. """Loads the XSL template file, replaces the variable strings,
  508. and returns the string of the XSL document."""
  509. self.xsl_body = self.open_template(XSL_TEMPLATE_LOCATION).substitute(
  510. xsd_namespace=XSD_NAMESPACE)
  511. return self.xsl_body
  512. def open_template(self, file_name):
  513. """It opens a template file, and it loads all lines to a
  514. string variable and returns string. Template object includes
  515. the variable. Limitation of a file size isn't needed there."""
  516. f = open(file_name, 'r')
  517. lines = "".join(f.readlines())
  518. f.close()
  519. assert lines is not None
  520. return string.Template(lines)
  521. if __name__ == "__main__":
  522. try:
  523. parser = OptionParser()
  524. parser.add_option(
  525. "-v", "--verbose", dest="verbose", action="store_true",
  526. help="enable maximum debug logging")
  527. (options, args) = parser.parse_args()
  528. if options.verbose:
  529. isc.log.init("b10-stats-httpd", "DEBUG", 99)
  530. stats_httpd = StatsHttpd()
  531. stats_httpd.start()
  532. except OptionValueError as ove:
  533. logger.fatal(STATHTTPD_BAD_OPTION_VALUE, ove)
  534. sys.exit(1)
  535. except isc.cc.session.SessionError as se:
  536. logger.fatal(STATHTTPD_CC_SESSION_ERROR, se)
  537. sys.exit(1)
  538. except HttpServerError as hse:
  539. logger.fatal(STATHTTPD_START_SERVER_INIT_ERROR, hse)
  540. sys.exit(1)
  541. except KeyboardInterrupt as kie:
  542. logger.info(STATHTTPD_STOPPED_BY_KEYBOARD)