stats_httpd.py.in 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. # If B10_FROM_SOURCE is set in the environment, we use data files
  33. # from a directory relative to that, otherwise we use the ones
  34. # installed on the system
  35. if "B10_FROM_SOURCE" in os.environ:
  36. BASE_LOCATION = os.environ["B10_FROM_SOURCE"]
  37. else:
  38. PREFIX = "@prefix@"
  39. DATAROOTDIR = "@datarootdir@"
  40. BASE_LOCATION = "@datadir@" + os.sep + "@PACKAGE@"
  41. BASE_LOCATION = BASE_LOCATION.replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  42. SPECFILE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd.spec"
  43. STATS_SPECFILE_LOCATION = BASE_LOCATION + os.sep + "stats.spec"
  44. XML_TEMPLATE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd-xml.tpl"
  45. XSD_TEMPLATE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd-xsd.tpl"
  46. XSL_TEMPLATE_LOCATION = BASE_LOCATION + os.sep + "stats-httpd-xsl.tpl"
  47. # These variables are paths part of URL.
  48. # eg. "http://${address}" + XXX_URL_PATH
  49. XML_URL_PATH = '/bind10/statistics/xml'
  50. XSD_URL_PATH = '/bind10/statistics/xsd'
  51. XSL_URL_PATH = '/bind10/statistics/xsl'
  52. # TODO: This should be considered later.
  53. XSD_NAMESPACE = 'http://bind10.isc.org' + XSD_URL_PATH
  54. DEFAULT_CONFIG = dict(listen_on=[('127.0.0.1', 8000)])
  55. # Assign this process name
  56. isc.util.process.rename()
  57. class HttpHandler(http.server.BaseHTTPRequestHandler):
  58. """HTTP handler class for HttpServer class. The class inhrits the super
  59. class http.server.BaseHTTPRequestHandler. It implemets do_GET()
  60. and do_HEAD() and orverrides log_message()"""
  61. def do_GET(self):
  62. body = self.send_head()
  63. if body is not None:
  64. self.wfile.write(body.encode())
  65. def do_HEAD(self):
  66. self.send_head()
  67. def send_head(self):
  68. try:
  69. if self.path == XML_URL_PATH:
  70. body = self.server.xml_handler()
  71. elif self.path == XSD_URL_PATH:
  72. body = self.server.xsd_handler()
  73. elif self.path == XSL_URL_PATH:
  74. body = self.server.xsl_handler()
  75. else:
  76. self.send_error(404)
  77. return None
  78. except StatsHttpdError as err:
  79. self.send_error(500)
  80. if self.server.verbose:
  81. self.server.log_writer(
  82. "[b10-stats-httpd] %s\n" % err)
  83. return None
  84. else:
  85. self.send_response(200)
  86. self.send_header("Content-type", "text/xml")
  87. self.send_header("Content-Length", len(body))
  88. self.end_headers()
  89. return body
  90. def log_message(self, format, *args):
  91. """Change the default log format"""
  92. if self.server.verbose:
  93. self.server.log_writer(
  94. "[b10-stats-httpd] %s - - [%s] %s\n" %
  95. (self.address_string(),
  96. self.log_date_time_string(),
  97. format%args))
  98. class HttpServerError(Exception):
  99. """Exception class for HttpServer class. It is intended to be
  100. passed from the HttpServer object to the StatsHttpd object."""
  101. pass
  102. class HttpServer(http.server.HTTPServer):
  103. """HTTP Server class. The class inherits the super
  104. http.server.HTTPServer. Some parameters are specified as
  105. arguments, which are xml_handler, xsd_handler, xsl_handler, and
  106. log_writer. These all are parameters which the StatsHttpd object
  107. has. The handler parameters are references of functions which
  108. return body of each document. The last parameter log_writer is
  109. reference of writer function to just write to
  110. sys.stderr.write. They are intended to be referred by HttpHandler
  111. object."""
  112. def __init__(self, server_address, handler,
  113. xml_handler, xsd_handler, xsl_handler, log_writer, verbose=False):
  114. self.server_address = server_address
  115. self.xml_handler = xml_handler
  116. self.xsd_handler = xsd_handler
  117. self.xsl_handler = xsl_handler
  118. self.log_writer = log_writer
  119. self.verbose = verbose
  120. http.server.HTTPServer.__init__(self, server_address, handler)
  121. class StatsHttpdError(Exception):
  122. """Exception class for StatsHttpd class. It is intended to be
  123. thrown from the the StatsHttpd object to the HttpHandler object or
  124. main routine."""
  125. pass
  126. class StatsHttpd:
  127. """The main class of HTTP server of HTTP/XML interface for
  128. statistics module. It handles HTTP requests, and command channel
  129. and config channel CC session. It uses select.select function
  130. while waiting for clients requests."""
  131. def __init__(self, verbose=False):
  132. self.verbose = verbose
  133. self.running = False
  134. self.poll_intval = 0.5
  135. self.write_log = sys.stderr.write
  136. self.mccs = None
  137. self.httpd = []
  138. self.open_mccs()
  139. self.load_config()
  140. self.load_templates()
  141. self.open_httpd()
  142. def open_mccs(self):
  143. """Opens a ModuleCCSession object"""
  144. # create ModuleCCSession
  145. if self.verbose:
  146. self.write_log("[b10-stats-httpd] Starting CC Session\n")
  147. self.mccs = isc.config.ModuleCCSession(
  148. SPECFILE_LOCATION, self.config_handler, self.command_handler)
  149. self.cc_session = self.mccs._session
  150. # read spec file of stats module and subscribe 'Stats'
  151. self.stats_module_spec = isc.config.module_spec_from_file(STATS_SPECFILE_LOCATION)
  152. self.stats_config_spec = self.stats_module_spec.get_config_spec()
  153. self.stats_module_name = self.stats_module_spec.get_module_name()
  154. def close_mccs(self):
  155. """Closes a ModuleCCSession object"""
  156. if self.mccs is None:
  157. return
  158. if self.verbose:
  159. self.write_log("[b10-stats-httpd] Closing CC Session\n")
  160. self.mccs.close()
  161. self.mccs = None
  162. def load_config(self, new_config={}):
  163. """Loads configuration from spec file or new configuration
  164. from the config manager"""
  165. # load config
  166. if len(new_config) > 0:
  167. self.config.update(new_config)
  168. else:
  169. self.config = DEFAULT_CONFIG
  170. self.config.update(
  171. dict([
  172. (itm['item_name'], self.mccs.get_value(itm['item_name'])[0])
  173. for itm in self.mccs.get_module_spec().get_config_spec()
  174. ])
  175. )
  176. # set addresses and ports for HTTP
  177. self.http_addrs = [ (cf['address'], cf['port']) for cf in self.config['listen_on'] ]
  178. def open_httpd(self):
  179. """Opens sockets for HTTP. Iterating each HTTP address to be
  180. configured in spec file"""
  181. for addr in self.http_addrs:
  182. self.httpd.append(self._open_httpd(addr))
  183. def _open_httpd(self, server_address, address_family=None):
  184. try:
  185. # try IPv6 at first
  186. if address_family is not None:
  187. HttpServer.address_family = address_family
  188. elif socket.has_ipv6:
  189. HttpServer.address_family = socket.AF_INET6
  190. httpd = HttpServer(
  191. server_address, HttpHandler,
  192. self.xml_handler, self.xsd_handler, self.xsl_handler,
  193. self.write_log, self.verbose)
  194. except (socket.gaierror, socket.error,
  195. OverflowError, TypeError) as err:
  196. # try IPv4 next
  197. if HttpServer.address_family == socket.AF_INET6:
  198. httpd = self._open_httpd(server_address, socket.AF_INET)
  199. else:
  200. raise HttpServerError(
  201. "Invalid address %s, port %s: %s: %s" %
  202. (server_address[0], server_address[1],
  203. err.__class__.__name__, err))
  204. else:
  205. if self.verbose:
  206. self.write_log(
  207. "[b10-stats-httpd] Started on address %s, port %s\n" %
  208. server_address)
  209. return httpd
  210. def close_httpd(self):
  211. """Closes sockets for HTTP"""
  212. if len(self.httpd) == 0:
  213. return
  214. for ht in self.httpd:
  215. if self.verbose:
  216. self.write_log(
  217. "[b10-stats-httpd] Closing address %s, port %s\n" %
  218. (ht.server_address[0], ht.server_address[1])
  219. )
  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. if self.verbose:
  255. self.write_log("[b10-stats-httpd] Shutting down\n")
  256. self.close_httpd()
  257. self.close_mccs()
  258. def get_sockets(self):
  259. """Returns sockets to select.select"""
  260. sockets = []
  261. if self.mccs is not None:
  262. sockets.append(self.mccs.get_socket())
  263. if len(self.httpd) > 0:
  264. for ht in self.httpd:
  265. sockets.append(ht.socket)
  266. return sockets
  267. def config_handler(self, new_config):
  268. """Config handler for the ModuleCCSession object. It resets
  269. addresses and ports to listen HTTP requests on."""
  270. if self.verbose:
  271. self.write_log("[b10-stats-httpd] Loading config : %s\n" % str(new_config))
  272. for key in new_config.keys():
  273. if key not in DEFAULT_CONFIG:
  274. if self.verbose:
  275. self.write_log(
  276. "[b10-stats-httpd] Unknown known config: %s" % key)
  277. return isc.config.ccsession.create_answer(
  278. 1, "Unknown known config: %s" % key)
  279. # backup old config
  280. old_config = self.config.copy()
  281. self.close_httpd()
  282. self.load_config(new_config)
  283. try:
  284. self.open_httpd()
  285. except HttpServerError as err:
  286. if self.verbose:
  287. self.write_log("[b10-stats-httpd] %s\n" % err)
  288. self.write_log("[b10-stats-httpd] Restoring old config\n")
  289. # restore old config
  290. self.config_handler(old_config)
  291. return isc.config.ccsession.create_answer(
  292. 1, "[b10-stats-httpd] %s" % err)
  293. else:
  294. return isc.config.ccsession.create_answer(0)
  295. def command_handler(self, command, args):
  296. """Command handler for the ModuleCCSesson object. It handles
  297. "status" and "shutdown" commands."""
  298. if command == "status":
  299. if self.verbose:
  300. self.write_log("[b10-stats-httpd] Received 'status' command\n")
  301. return isc.config.ccsession.create_answer(
  302. 0, "Stats Httpd is up. (PID " + str(os.getpid()) + ")")
  303. elif command == "shutdown":
  304. if self.verbose:
  305. self.write_log("[b10-stats-httpd] Received 'shutdown' command\n")
  306. self.running = False
  307. return isc.config.ccsession.create_answer(
  308. 0, "Stats Httpd is shutting down.")
  309. else:
  310. if self.verbose:
  311. self.write_log("[b10-stats-httpd] Received unknown command\n")
  312. return isc.config.ccsession.create_answer(
  313. 1, "Unknown command: " + str(command))
  314. def get_stats_data(self):
  315. """Requests statistics data to the Stats daemon and returns
  316. the data which obtains from it"""
  317. try:
  318. seq = self.cc_session.group_sendmsg(
  319. isc.config.ccsession.create_command('show'),
  320. self.stats_module_name)
  321. (answer, env) = self.cc_session.group_recvmsg(False, seq)
  322. if answer:
  323. (rcode, value) = isc.config.ccsession.parse_answer(answer)
  324. except (isc.cc.session.SessionTimeout,
  325. isc.cc.session.SessionError) as err:
  326. raise StatsHttpdError("%s: %s" %
  327. (err.__class__.__name__, err))
  328. else:
  329. if rcode == 0:
  330. return value
  331. else:
  332. raise StatsHttpdError("Stats module: %s" % str(value))
  333. def get_stats_spec(self):
  334. """Just returns spec data"""
  335. return self.stats_config_spec
  336. def load_templates(self):
  337. """Setup the bodies of XSD and XSL documents to be responds to
  338. HTTP clients. Before that it also creates XML tag structures by
  339. using xml.etree.ElementTree.Element class and substitutes
  340. concrete strings with parameters embed in the string.Template
  341. object."""
  342. # for XSD
  343. xsd_root = xml.etree.ElementTree.Element("all") # started with "all" tag
  344. for item in self.get_stats_spec():
  345. element = xml.etree.ElementTree.Element(
  346. "element",
  347. dict( name=item["item_name"],
  348. type=item["item_type"] if item["item_type"].lower() != 'real' else 'float',
  349. minOccurs="1",
  350. maxOccurs="1" ),
  351. )
  352. annotation = xml.etree.ElementTree.Element("annotation")
  353. appinfo = xml.etree.ElementTree.Element("appinfo")
  354. documentation = xml.etree.ElementTree.Element("documentation")
  355. appinfo.text = item["item_title"]
  356. documentation.text = item["item_description"]
  357. annotation.append(appinfo)
  358. annotation.append(documentation)
  359. element.append(annotation)
  360. xsd_root.append(element)
  361. xsd_string = xml.etree.ElementTree.tostring(xsd_root)
  362. self.xsd_body = self.open_template(XSD_TEMPLATE_LOCATION).substitute(
  363. xsd_string=xsd_string,
  364. xsd_namespace=XSD_NAMESPACE
  365. )
  366. assert self.xsd_body is not None
  367. # for XSL
  368. xsd_root = xml.etree.ElementTree.Element(
  369. "xsl:template",
  370. dict(match="*")) # started with xml:template tag
  371. for item in self.get_stats_spec():
  372. tr = xml.etree.ElementTree.Element("tr")
  373. td1 = xml.etree.ElementTree.Element(
  374. "td", { "class" : "title",
  375. "title" : item["item_description"] })
  376. td1.text = item["item_title"]
  377. td2 = xml.etree.ElementTree.Element("td")
  378. xsl_valueof = xml.etree.ElementTree.Element(
  379. "xsl:value-of",
  380. dict(select=item["item_name"]))
  381. td2.append(xsl_valueof)
  382. tr.append(td1)
  383. tr.append(td2)
  384. xsd_root.append(tr)
  385. xsl_string = xml.etree.ElementTree.tostring(xsd_root)
  386. self.xsl_body = self.open_template(XSL_TEMPLATE_LOCATION).substitute(
  387. xsl_string=xsl_string,
  388. xsd_namespace=XSD_NAMESPACE)
  389. assert self.xsl_body is not None
  390. def xml_handler(self):
  391. """Handler which requests to Stats daemon to obtain statistics
  392. data and returns the body of XML document"""
  393. xml_list=[]
  394. for (k, v) in self.get_stats_data().items():
  395. (k, v) = (str(k), str(v))
  396. elem = xml.etree.ElementTree.Element(k)
  397. elem.text = v
  398. xml_list.append(
  399. xml.etree.ElementTree.tostring(elem))
  400. xml_string = "".join(xml_list)
  401. self.xml_body = self.open_template(XML_TEMPLATE_LOCATION).substitute(
  402. xml_string=xml_string,
  403. xsd_namespace=XSD_NAMESPACE,
  404. xsd_url_path=XSD_URL_PATH,
  405. xsl_url_path=XSL_URL_PATH)
  406. assert self.xml_body is not None
  407. return self.xml_body
  408. def xsd_handler(self):
  409. """Handler which just returns the body of XSD document"""
  410. return self.xsd_body
  411. def xsl_handler(self):
  412. """Handler which just returns the body of XSL document"""
  413. return self.xsl_body
  414. def open_template(self, file_name):
  415. """It opens a template file, and it loads all lines to a
  416. string variable and returns string. Template object includes
  417. the variable. Limitation of a file size isn't needed there."""
  418. lines = "".join(
  419. open(file_name, 'r').readlines())
  420. assert lines is not None
  421. return string.Template(lines)
  422. if __name__ == "__main__":
  423. try:
  424. parser = OptionParser()
  425. parser.add_option(
  426. "-v", "--verbose", dest="verbose", action="store_true",
  427. help="display more about what is going on")
  428. (options, args) = parser.parse_args()
  429. stats_httpd = StatsHttpd(verbose=options.verbose)
  430. stats_httpd.start()
  431. except OptionValueError:
  432. sys.exit("[b10-stats-httpd] Error parsing options")
  433. except isc.cc.session.SessionError as se:
  434. sys.exit("[b10-stats-httpd] Error creating module, "
  435. + "is the command channel daemon running?")
  436. except HttpServerError as hse:
  437. sys.exit("[b10-stats-httpd] %s" % hse)
  438. except KeyboardInterrupt as kie:
  439. sys.exit("[b10-stats-httpd] Interrupted, exiting")