stats_httpd.py.in 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. #!@PYTHON@
  2. # Copyright (C) 2011 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 isc.cc
  30. import isc.config
  31. import isc.util.process
  32. import isc.log
  33. from isc.log_messages.stats_httpd_messages import *
  34. isc.log.init("b10-stats-httpd")
  35. logger = isc.log.Logger("stats-httpd")
  36. # Some constants for debug levels, these should be removed when we
  37. # have #1074
  38. DBG_STATHTTPD_INIT = 10
  39. DBG_STATHTTPD_MESSAGING = 30
  40. # If B10_FROM_SOURCE is set in the environment, we use data files
  41. # from a directory relative to that, otherwise we use the ones
  42. # installed on the system
  43. if "B10_FROM_SOURCE" in os.environ:
  44. BASE_LOCATION = os.environ["B10_FROM_SOURCE"] + os.sep + \
  45. "src" + os.sep + "bin" + os.sep + "stats"
  46. else:
  47. PREFIX = "@prefix@"
  48. DATAROOTDIR = "@datarootdir@"
  49. BASE_LOCATION = "@datadir@" + os.sep + "@PACKAGE@"
  50. BASE_LOCATION = BASE_LOCATION.replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  51. SPECFILE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd.spec"
  52. SCHEMA_SPECFILE_LOCATION = BASE_LOCATION + os.sep + "stats-schema.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' + XSD_URL_PATH
  63. DEFAULT_CONFIG = dict(listen_on=[('127.0.0.1', 8000)])
  64. # Assign this process name
  65. isc.util.process.rename()
  66. class HttpHandler(http.server.BaseHTTPRequestHandler):
  67. """HTTP handler class for HttpServer class. The class inhrits the super
  68. class http.server.BaseHTTPRequestHandler. It implemets do_GET()
  69. and do_HEAD() and orverrides log_message()"""
  70. def do_GET(self):
  71. body = self.send_head()
  72. if body is not None:
  73. self.wfile.write(body.encode())
  74. def do_HEAD(self):
  75. self.send_head()
  76. def send_head(self):
  77. try:
  78. if self.path == XML_URL_PATH:
  79. body = self.server.xml_handler()
  80. elif self.path == XSD_URL_PATH:
  81. body = self.server.xsd_handler()
  82. elif self.path == XSL_URL_PATH:
  83. body = self.server.xsl_handler()
  84. else:
  85. if self.path == '/' and 'Host' in self.headers.keys():
  86. # redirect to XML URL only when requested with '/'
  87. self.send_response(302)
  88. self.send_header(
  89. "Location",
  90. "http://" + self.headers.get('Host') + XML_URL_PATH)
  91. self.end_headers()
  92. return None
  93. else:
  94. # Couldn't find HOST
  95. self.send_error(404)
  96. return None
  97. except StatsHttpdError as err:
  98. self.send_error(500)
  99. logger.error(STATHTTPD_SERVER_ERROR, err)
  100. return None
  101. else:
  102. self.send_response(200)
  103. self.send_header("Content-type", "text/xml")
  104. self.send_header("Content-Length", len(body))
  105. self.end_headers()
  106. return body
  107. class HttpServerError(Exception):
  108. """Exception class for HttpServer class. It is intended to be
  109. passed from the HttpServer object to the StatsHttpd object."""
  110. pass
  111. class HttpServer(http.server.HTTPServer):
  112. """HTTP Server class. The class inherits the super
  113. http.server.HTTPServer. Some parameters are specified as
  114. arguments, which are xml_handler, xsd_handler, xsl_handler, and
  115. log_writer. These all are parameters which the StatsHttpd object
  116. has. The handler parameters are references of functions which
  117. return body of each document. The last parameter log_writer is
  118. reference of writer function to just write to
  119. sys.stderr.write. They are intended to be referred by HttpHandler
  120. object."""
  121. def __init__(self, server_address, handler,
  122. xml_handler, xsd_handler, xsl_handler, log_writer):
  123. self.server_address = server_address
  124. self.xml_handler = xml_handler
  125. self.xsd_handler = xsd_handler
  126. self.xsl_handler = xsl_handler
  127. self.log_writer = log_writer
  128. http.server.HTTPServer.__init__(self, server_address, handler)
  129. class StatsHttpdError(Exception):
  130. """Exception class for StatsHttpd class. It is intended to be
  131. thrown from the the StatsHttpd object to the HttpHandler object or
  132. main routine."""
  133. pass
  134. class StatsHttpd:
  135. """The main class of HTTP server of HTTP/XML interface for
  136. statistics module. It handles HTTP requests, and command channel
  137. and config channel CC session. It uses select.select function
  138. while waiting for clients requests."""
  139. def __init__(self):
  140. self.running = False
  141. self.poll_intval = 0.5
  142. self.write_log = sys.stderr.write
  143. self.mccs = None
  144. self.httpd = []
  145. self.open_mccs()
  146. self.load_config()
  147. self.load_templates()
  148. self.open_httpd()
  149. def open_mccs(self):
  150. """Opens a ModuleCCSession object"""
  151. # create ModuleCCSession
  152. logger.debug(DBG_STATHTTPD_INIT, STATHTTPD_STARTING_CC_SESSION)
  153. self.mccs = isc.config.ModuleCCSession(
  154. SPECFILE_LOCATION, self.config_handler, self.command_handler)
  155. self.cc_session = self.mccs._session
  156. # read spec file of stats module and subscribe 'Stats'
  157. self.stats_module_spec = isc.config.module_spec_from_file(SCHEMA_SPECFILE_LOCATION)
  158. self.stats_config_spec = self.stats_module_spec.get_config_spec()
  159. self.stats_module_name = self.stats_module_spec.get_module_name()
  160. def close_mccs(self):
  161. """Closes a ModuleCCSession object"""
  162. if self.mccs is None:
  163. return
  164. logger.debug(DBG_STATHTTPD_INIT, STATHTTPD_CLOSING_CC_SESSION)
  165. self.mccs.close()
  166. self.mccs = None
  167. def load_config(self, new_config={}):
  168. """Loads configuration from spec file or new configuration
  169. from the config manager"""
  170. # load config
  171. if len(new_config) > 0:
  172. self.config.update(new_config)
  173. else:
  174. self.config = DEFAULT_CONFIG
  175. self.config.update(
  176. dict([
  177. (itm['item_name'], self.mccs.get_value(itm['item_name'])[0])
  178. for itm in self.mccs.get_module_spec().get_config_spec()
  179. ])
  180. )
  181. # set addresses and ports for HTTP
  182. self.http_addrs = [ (cf['address'], cf['port']) for cf in self.config['listen_on'] ]
  183. def open_httpd(self):
  184. """Opens sockets for HTTP. Iterating each HTTP address to be
  185. configured in spec file"""
  186. for addr in self.http_addrs:
  187. self.httpd.append(self._open_httpd(addr))
  188. def _open_httpd(self, server_address, address_family=None):
  189. try:
  190. # try IPv6 at first
  191. if address_family is not None:
  192. HttpServer.address_family = address_family
  193. elif socket.has_ipv6:
  194. HttpServer.address_family = socket.AF_INET6
  195. httpd = HttpServer(
  196. server_address, HttpHandler,
  197. self.xml_handler, self.xsd_handler, self.xsl_handler,
  198. self.write_log)
  199. except (socket.gaierror, socket.error,
  200. OverflowError, TypeError) as err:
  201. # try IPv4 next
  202. if HttpServer.address_family == socket.AF_INET6:
  203. httpd = self._open_httpd(server_address, socket.AF_INET)
  204. else:
  205. raise HttpServerError(
  206. "Invalid address %s, port %s: %s: %s" %
  207. (server_address[0], server_address[1],
  208. err.__class__.__name__, err))
  209. else:
  210. logger.info(STATHTTPD_STARTED, server_address[0],
  211. server_address[1])
  212. return httpd
  213. def close_httpd(self):
  214. """Closes sockets for HTTP"""
  215. if len(self.httpd) == 0:
  216. return
  217. for ht in self.httpd:
  218. logger.info(STATHTTPD_CLOSING, ht.server_address[0],
  219. ht.server_address[1])
  220. ht.server_close()
  221. self.httpd = []
  222. def start(self):
  223. """Starts StatsHttpd objects to run. Waiting for client
  224. requests by using select.select functions"""
  225. self.mccs.start()
  226. self.running = True
  227. while self.running:
  228. try:
  229. (rfd, wfd, xfd) = select.select(
  230. self.get_sockets(), [], [], self.poll_intval)
  231. except select.error as err:
  232. # select.error exception is caught only in the case of
  233. # EINTR, or in other cases it is just thrown.
  234. if err.args[0] == errno.EINTR:
  235. (rfd, wfd, xfd) = ([], [], [])
  236. else:
  237. raise
  238. # FIXME: This module can handle only one request at a
  239. # time. If someone sends only part of the request, we block
  240. # waiting for it until we time out.
  241. # But it isn't so big issue for administration purposes.
  242. for fd in rfd + xfd:
  243. if fd == self.mccs.get_socket():
  244. self.mccs.check_command(nonblock=False)
  245. continue
  246. for ht in self.httpd:
  247. if fd == ht.socket:
  248. ht.handle_request()
  249. break
  250. self.stop()
  251. def stop(self):
  252. """Stops the running StatsHttpd objects. Closes CC session and
  253. HTTP handling sockets"""
  254. logger.info(STATHTTPD_SHUTDOWN)
  255. self.close_httpd()
  256. self.close_mccs()
  257. def get_sockets(self):
  258. """Returns sockets to select.select"""
  259. sockets = []
  260. if self.mccs is not None:
  261. sockets.append(self.mccs.get_socket())
  262. if len(self.httpd) > 0:
  263. for ht in self.httpd:
  264. sockets.append(ht.socket)
  265. return sockets
  266. def config_handler(self, new_config):
  267. """Config handler for the ModuleCCSession object. It resets
  268. addresses and ports to listen HTTP requests on."""
  269. logger.debug(DBG_STATHTTPD_MESSAGING, STATHTTPD_HANDLE_CONFIG,
  270. new_config)
  271. for key in new_config.keys():
  272. if key not in DEFAULT_CONFIG and key != "version":
  273. logger.error(STATHTTPD_UNKNOWN_CONFIG_ITEM, key)
  274. return isc.config.ccsession.create_answer(
  275. 1, "Unknown known config: %s" % key)
  276. # backup old config
  277. old_config = self.config.copy()
  278. self.close_httpd()
  279. self.load_config(new_config)
  280. try:
  281. self.open_httpd()
  282. except HttpServerError as err:
  283. logger.error(STATHTTPD_SERVER_ERROR, err)
  284. # restore old config
  285. self.config_handler(old_config)
  286. return isc.config.ccsession.create_answer(
  287. 1, "[b10-stats-httpd] %s" % err)
  288. else:
  289. return isc.config.ccsession.create_answer(0)
  290. def command_handler(self, command, args):
  291. """Command handler for the ModuleCCSesson object. It handles
  292. "status" and "shutdown" commands."""
  293. if command == "status":
  294. logger.debug(DBG_STATHTTPD_MESSAGING,
  295. STATHTTPD_RECEIVED_STATUS_COMMAND)
  296. return isc.config.ccsession.create_answer(
  297. 0, "Stats Httpd is up. (PID " + str(os.getpid()) + ")")
  298. elif command == "shutdown":
  299. logger.debug(DBG_STATHTTPD_MESSAGING,
  300. STATHTTPD_RECEIVED_SHUTDOWN_COMMAND)
  301. self.running = False
  302. return isc.config.ccsession.create_answer(
  303. 0, "Stats Httpd is shutting down.")
  304. else:
  305. logger.debug(DBG_STATHTTPD_MESSAGING,
  306. STATHTTPD_RECEIVED_UNKNOWN_COMMAND, command)
  307. return isc.config.ccsession.create_answer(
  308. 1, "Unknown command: " + str(command))
  309. def get_stats_data(self):
  310. """Requests statistics data to the Stats daemon and returns
  311. the data which obtains from it"""
  312. try:
  313. seq = self.cc_session.group_sendmsg(
  314. isc.config.ccsession.create_command('show'),
  315. self.stats_module_name)
  316. (answer, env) = self.cc_session.group_recvmsg(False, seq)
  317. if answer:
  318. (rcode, value) = isc.config.ccsession.parse_answer(answer)
  319. except (isc.cc.session.SessionTimeout,
  320. isc.cc.session.SessionError) as err:
  321. raise StatsHttpdError("%s: %s" %
  322. (err.__class__.__name__, err))
  323. else:
  324. if rcode == 0:
  325. return value
  326. else:
  327. raise StatsHttpdError("Stats module: %s" % str(value))
  328. def get_stats_spec(self):
  329. """Just returns spec data"""
  330. return self.stats_config_spec
  331. def load_templates(self):
  332. """Setup the bodies of XSD and XSL documents to be responds to
  333. HTTP clients. Before that it also creates XML tag structures by
  334. using xml.etree.ElementTree.Element class and substitutes
  335. concrete strings with parameters embed in the string.Template
  336. object."""
  337. # for XSD
  338. xsd_root = xml.etree.ElementTree.Element("all") # started with "all" tag
  339. for item in self.get_stats_spec():
  340. element = xml.etree.ElementTree.Element(
  341. "element",
  342. dict( name=item["item_name"],
  343. type=item["item_type"] if item["item_type"].lower() != 'real' else 'float',
  344. minOccurs="1",
  345. maxOccurs="1" ),
  346. )
  347. annotation = xml.etree.ElementTree.Element("annotation")
  348. appinfo = xml.etree.ElementTree.Element("appinfo")
  349. documentation = xml.etree.ElementTree.Element("documentation")
  350. appinfo.text = item["item_title"]
  351. documentation.text = item["item_description"]
  352. annotation.append(appinfo)
  353. annotation.append(documentation)
  354. element.append(annotation)
  355. xsd_root.append(element)
  356. # The coding conversion is tricky. xml..tostring() of Python 3.2
  357. # returns bytes (not string) regardless of the coding, while
  358. # tostring() of Python 3.1 returns a string. To support both
  359. # cases transparently, we first make sure tostring() returns
  360. # bytes by specifying utf-8 and then convert the result to a
  361. # plain string (code below assume it).
  362. xsd_string = str(xml.etree.ElementTree.tostring(xsd_root, encoding='utf-8'),
  363. encoding='us-ascii')
  364. self.xsd_body = self.open_template(XSD_TEMPLATE_LOCATION).substitute(
  365. xsd_string=xsd_string,
  366. xsd_namespace=XSD_NAMESPACE
  367. )
  368. assert self.xsd_body is not None
  369. # for XSL
  370. xsd_root = xml.etree.ElementTree.Element(
  371. "xsl:template",
  372. dict(match="*")) # started with xml:template tag
  373. for item in self.get_stats_spec():
  374. tr = xml.etree.ElementTree.Element("tr")
  375. td1 = xml.etree.ElementTree.Element(
  376. "td", { "class" : "title",
  377. "title" : item["item_description"] })
  378. td1.text = item["item_title"]
  379. td2 = xml.etree.ElementTree.Element("td")
  380. xsl_valueof = xml.etree.ElementTree.Element(
  381. "xsl:value-of",
  382. dict(select=item["item_name"]))
  383. td2.append(xsl_valueof)
  384. tr.append(td1)
  385. tr.append(td2)
  386. xsd_root.append(tr)
  387. # The coding conversion is tricky. xml..tostring() of Python 3.2
  388. # returns bytes (not string) regardless of the coding, while
  389. # tostring() of Python 3.1 returns a string. To support both
  390. # cases transparently, we first make sure tostring() returns
  391. # bytes by specifying utf-8 and then convert the result to a
  392. # plain string (code below assume it).
  393. xsl_string = str(xml.etree.ElementTree.tostring(xsd_root, encoding='utf-8'),
  394. encoding='us-ascii')
  395. self.xsl_body = self.open_template(XSL_TEMPLATE_LOCATION).substitute(
  396. xsl_string=xsl_string,
  397. xsd_namespace=XSD_NAMESPACE)
  398. assert self.xsl_body is not None
  399. def xml_handler(self):
  400. """Handler which requests to Stats daemon to obtain statistics
  401. data and returns the body of XML document"""
  402. xml_list=[]
  403. for (k, v) in self.get_stats_data().items():
  404. (k, v) = (str(k), str(v))
  405. elem = xml.etree.ElementTree.Element(k)
  406. elem.text = v
  407. # The coding conversion is tricky. xml..tostring() of Python 3.2
  408. # returns bytes (not string) regardless of the coding, while
  409. # tostring() of Python 3.1 returns a string. To support both
  410. # cases transparently, we first make sure tostring() returns
  411. # bytes by specifying utf-8 and then convert the result to a
  412. # plain string (code below assume it).
  413. xml_list.append(
  414. str(xml.etree.ElementTree.tostring(elem, encoding='utf-8'),
  415. encoding='us-ascii'))
  416. xml_string = "".join(xml_list)
  417. self.xml_body = self.open_template(XML_TEMPLATE_LOCATION).substitute(
  418. xml_string=xml_string,
  419. xsd_namespace=XSD_NAMESPACE,
  420. xsd_url_path=XSD_URL_PATH,
  421. xsl_url_path=XSL_URL_PATH)
  422. assert self.xml_body is not None
  423. return self.xml_body
  424. def xsd_handler(self):
  425. """Handler which just returns the body of XSD document"""
  426. return self.xsd_body
  427. def xsl_handler(self):
  428. """Handler which just returns the body of XSL document"""
  429. return self.xsl_body
  430. def open_template(self, file_name):
  431. """It opens a template file, and it loads all lines to a
  432. string variable and returns string. Template object includes
  433. the variable. Limitation of a file size isn't needed there."""
  434. lines = "".join(
  435. open(file_name, 'r').readlines())
  436. assert lines is not None
  437. return string.Template(lines)
  438. if __name__ == "__main__":
  439. try:
  440. parser = OptionParser()
  441. parser.add_option(
  442. "-v", "--verbose", dest="verbose", action="store_true",
  443. help="display more about what is going on")
  444. (options, args) = parser.parse_args()
  445. if options.verbose:
  446. isc.log.init("b10-stats-httpd", "DEBUG", 99)
  447. stats_httpd = StatsHttpd()
  448. stats_httpd.start()
  449. except OptionValueError as ove:
  450. logger.fatal(STATHTTPD_BAD_OPTION_VALUE, ove)
  451. sys.exit(1)
  452. except isc.cc.session.SessionError as se:
  453. logger.fatal(STATHTTPD_CC_SESSION_ERROR, se)
  454. sys.exit(1)
  455. except HttpServerError as hse:
  456. logger.fatal(STATHTTPD_START_SERVER_ERROR, hse)
  457. sys.exit(1)
  458. except KeyboardInterrupt as kie:
  459. logger.info(STATHTTPD_STOPPED_BY_KEYBOARD)