Coverage for src/bin/stats/stats_httpd : 93%
        
        
Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
| 
 #!/usr/bin/python3 
 # Copyright (C) 2011 Internet Systems Consortium. # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 
 A standalone HTTP server for HTTP/XML interface of statistics in BIND 10 
 """ 
 
 
 
 # Some constants for debug levels. 
 # If B10_FROM_SOURCE is set in the environment, we use data files # from a directory relative to that, otherwise we use the ones # installed on the system "src" + os.sep + "bin" + os.sep + "stats" else: 
 # These variables are paths part of URL. # eg. "http://${address}" + XXX_URL_PATH # TODO: This should be considered later. 
 # Assign this process name 
 """HTTP handler class for HttpServer class. The class inhrits the super class http.server.BaseHTTPRequestHandler. It implemets do_GET() and do_HEAD() and orverrides log_message()""" 
 
 # in case of /bind10/statistics/xxx/YYY/zzz # in case of /bind10/statistics/xxx/YYY ... else: # redirect to XML URL only when requested with '/' "Location", "http://" + self.headers.get('Host') + XML_URL_PATH) else: # Couldn't find HOST # Couldn't find neither specified module name nor # specified item name else: 
 """Exception class for HttpServer class. It is intended to be passed from the HttpServer object to the StatsHttpd object.""" 
 """HTTP Server class. The class inherits the super http.server.HTTPServer. Some parameters are specified as arguments, which are xml_handler, xsd_handler, xsl_handler, and log_writer. These all are parameters which the StatsHttpd object has. The handler parameters are references of functions which return body of each document. The last parameter log_writer is reference of writer function to just write to sys.stderr.write. They are intended to be referred by HttpHandler object.""" xml_handler, xsd_handler, xsl_handler, log_writer): 
 """Exception class for StatsHttpd class. It is intended to be thrown from the the StatsHttpd object to the HttpHandler object or main routine.""" 
 """Exception class for StatsHttpd class. The reason seems to be due to the data. It is intended to be thrown from the the StatsHttpd object to the HttpHandler object or main routine.""" 
 """The main class of HTTP server of HTTP/XML interface for statistics module. It handles HTTP requests, and command channel and config channel CC session. It uses select.select function while waiting for clients requests.""" # if some exception, e.g. address in use, is raised, then it closes mccs and httpd 
 """Opens a ModuleCCSession object""" # create ModuleCCSession SPECFILE_LOCATION, self.config_handler, self.command_handler) 
 """Closes a ModuleCCSession object""" 
 
 """Loads configuration from spec file or new configuration from the config manager""" # load config (itm['item_name'], self.mccs.get_value(itm['item_name'])[0]) for itm in self.mccs.get_module_spec().get_config_spec() ]) # set addresses and ports for HTTP 
 """Opens sockets for HTTP. Iterating each HTTP address to be configured in spec file""" 
 # get address family for the server_address before # creating HttpServer object. If a specified address is # not numerical, gaierror may be thrown. server_address[0], server_address[1], 0, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_NUMERICHOST )[0][0] server_address, HttpHandler, self.xml_handler, self.xsd_handler, self.xsl_handler, self.write_log) server_address[1]) OverflowError, TypeError) as err: httpd.server_close() "Invalid address %s, port %s: %s: %s" % (server_address[0], server_address[1], err.__class__.__name__, err)) 
 """Closes sockets for HTTP""" ht.server_address[1]) 
 """Starts StatsHttpd objects to run. Waiting for client requests by using select.select functions""" self.get_sockets(), [], [], self.poll_intval) # select.error exception is caught only in the case of # EINTR, or in other cases it is just thrown. else: # FIXME: This module can handle only one request at a # time. If someone sends only part of the request, we block # waiting for it until we time out. # But it isn't so big issue for administration purposes. 
 """Stops the running StatsHttpd objects. Closes CC session and HTTP handling sockets""" 
 """Returns sockets to select.select""" 
 """Config handler for the ModuleCCSession object. It resets addresses and ports to listen HTTP requests on.""" new_config) validate_config(False, new_config, errors): 1, ", ".join(errors)) # backup old config # If the http sockets aren't opened or # if new_config doesn't have'listen_on', it returns # restore old config else: 
 """Command handler for the ModuleCCSesson object. It handles "status" and "shutdown" commands.""" STATHTTPD_RECEIVED_STATUS_COMMAND) 0, "Stats Httpd is up. (PID " + str(os.getpid()) + ")") STATHTTPD_RECEIVED_SHUTDOWN_COMMAND) else: STATHTTPD_RECEIVED_UNKNOWN_COMMAND, command) 1, "Unknown command: " + str(command)) 
 """Requests statistics data to the Stats daemon and returns the data which obtains from it. The first argument is the module name which owns the statistics data, the second argument is one name of the statistics items which the the module owns. The second argument cannot be specified when the first argument is not specified. It returns the statistics data of the specified module or item. When the session timeout or the session error is occurred, it raises StatsHttpdError. When the stats daemon returns none-zero value, it raises StatsHttpdDataError.""" isc.config.ccsession.create_command('show', param), 'Stats') except (isc.cc.session.SessionTimeout, isc.cc.session.SessionError) as err: raise StatsHttpdError("%s: %s" % (err.__class__.__name__, err)) else: else: raise StatsHttpdDataError("Stats module: %s" % str(value)) 
 """Requests statistics data to the Stats daemon and returns the data which obtains from it. The first argument is the module name which owns the statistics data, the second argument is one name of the statistics items which the the module owns. The second argument cannot be specified when the first argument is not specified. It returns the statistics specification of the specified module or item. When the session timeout or the session error is occurred, it raises StatsHttpdError. When the stats daemon returns none-zero value, it raises StatsHttpdDataError.""" isc.config.ccsession.create_command('showschema', param), 'Stats') else: isc.cc.session.SessionError) as err: (err.__class__.__name__, err)) 
 
 """Requests the specified statistics data and specification by using the functions get_stats_data and get_stats_spec respectively and loads the XML template file and returns the string of the XML document.The first argument is the module name which owns the statistics data, the second argument is one name of the statistics items which the the module owns. The second argument cannot be specified when the first argument is not specified.""" 
 # TODO: Separate the following recursive function by type of # the parameter. Because we should be sure what type there is # when we call it recursively. """Internal use for xml_handler. Reads stats_data and stats_spec specified as first and second arguments, and modify the xml object specified as third argument. xml_elem must be modified and always returns None.""" # assumed started with module_spec or started with # item_spec in statistics # assumed started with module_spec and 'item_type' not in stats_spec: stats_data[module_name], elem) # started with item_spec in statistics else: stats_data, elem) item, elem) else: # assumed started with stats_spec stats_data[item_spec['item_name']], xml_elem) 
 # make the path xxx/module/item if specified respectively 'bind10:statistics', attrib={ 'xsi:schemaLocation' : XSD_NAMESPACE + ' ' + XSD_URL_PATH + path_info, 'xmlns:bind10' : XSD_NAMESPACE, 'xmlns:xsi' : "http://www.w3.org/2001/XMLSchema-instance" }) # The coding conversion is tricky. xml..tostring() of Python 3.2 # returns bytes (not string) regardless of the coding, while # tostring() of Python 3.1 returns a string. To support both # cases transparently, we first make sure tostring() returns # bytes by specifying utf-8 and then convert the result to a # plain string (code below assume it). # FIXME: Non-ASCII characters might be lost here. Consider how # the whole system should handle non-ASCII characters. encoding='us-ascii') xml_string=xml_string, xsl_url_path=XSL_URL_PATH + path_info) 
 """Requests the specified statistics specification by using the function get_stats_spec respectively and loads the XSD template file and returns the string of the XSD document.The first argument is the module name which owns the statistics data, the second argument is one name of the statistics items which the the module owns. The second argument cannot be specified when the first argument is not specified.""" 
 # TODO: Separate the following recursive function by type of # the parameter. Because we should be sure what type there is # when we call it recursively. """Internal use for xsd_handler. Reads stats_spec specified as first arguments, and modify the xml object specified as second argument. xsd_elem must be modified. Always returns None with no exceptions.""" # assumed module_spec or one stats_spec # assumed module_spec "element", { "name" : mod }) # assumed stats_spec else: "element", attrib={ "name" : stats_spec["item_name"], "minOccurs": "0" \ if stats_spec["item_optional"] \ else "1", "maxOccurs": "unbounded" }) "element", attrib={ "name" : stats_spec["item_name"], "minOccurs": "0" \ if stats_spec["item_optional"] \ else "1", "maxOccurs": "1" }) else: # determine the datatype of XSD # TODO: Should consider other item_format types if stats_spec["item_type"].lower() != 'real' \ else 'float' and item_format.lower() == 'date-time': elif datatype.lower() == 'string' \ and (item_format.lower() == 'date' \ or item_format.lower() == 'time'): datatype = item_format.lower() "element", attrib={ 'name' : stats_spec["item_name"], 'type' : datatype, 'minOccurs' : "0" \ if stats_spec["item_optional"] \ else "1", 'maxOccurs' : "1" } ) # multiple stats_specs 
 # for XSD "element", attrib={ 'name' : 'statistics' }) "schema", attrib={ 'xmlns' : "http://www.w3.org/2001/XMLSchema", 'targetNamespace' : XSD_NAMESPACE, 'xmlns:bind10' : XSD_NAMESPACE }) # The coding conversion is tricky. xml..tostring() of Python 3.2 # returns bytes (not string) regardless of the coding, while # tostring() of Python 3.1 returns a string. To support both # cases transparently, we first make sure tostring() returns # bytes by specifying utf-8 and then convert the result to a # plain string (code below assume it). # FIXME: Non-ASCII characters might be lost here. Consider how # the whole system should handle non-ASCII characters. encoding='us-ascii') xsd_string=xsd_string) 
 """Requests the specified statistics specification by using the function get_stats_spec respectively and loads the XSL template file and returns the string of the XSL document.The first argument is the module name which owns the statistics data, the second argument is one name of the statistics items which the the module owns. The second argument cannot be specified when the first argument is not specified.""" 
 # TODO: Separate the following recursive function by type of # the parameter. Because we should be sure what type there is # when we call it recursively. """Internal use for xsl_handler. Reads stats_spec specified as first arguments, and modify the xml object specified as second argument. xsl_elem must be modified. The third argument is a base path used for making anchor tag in XSL. Always returns None with no exceptions.""" # assumed module_spec or one stats_spec # assumed module_spec "xsl:for-each", attrib={ "select" : mod }) "a", attrib={ "href": urllib.parse.quote(path + "/" + mod) }) path + "/" + mod) # assumed stats_spec else: "xsl:for-each", attrib={ "select" : stats_spec['item_name'] }) "td", attrib={ "class" : "title", "title" : stats_spec["item_description"] \ if "item_description" in stats_spec \ else "" }) # TODO: Consider whether we should always use # the identical name "item_name" for the # user-visible name in XSL. path + "/" + stats_spec["item_name"]) path + "/" + stats_spec["item_name"]) else: "xsl:value-of", attrib={'select': stats_spec["item_name"]}) 
 # multiple stats_specs "td", attrib={ "class" : "title", "title" : item_spec["item_description"] \ if "item_description" in item_spec \ else "" }) # if the path length is equal to or shorter than # XML_URL_PATH + /Module/Item, add the anchor tag. "a", attrib={ "href": urllib.parse.quote(path + "/" + item_spec["item_name"]) }) else: "xsl:for-each", attrib={ "select" : item_spec['item_name'] }) else: 
 # for XSL "xsl:template", attrib={'match': "bind10:statistics"}) # The coding conversion is tricky. xml..tostring() of Python 3.2 # returns bytes (not string) regardless of the coding, while # tostring() of Python 3.1 returns a string. To support both # cases transparently, we first make sure tostring() returns # bytes by specifying utf-8 and then convert the result to a # plain string (code below assume it). # FIXME: Non-ASCII characters might be lost here. Consider how # the whole system should handle non-ASCII characters. encoding='us-ascii') xsl_string=xsl_string, xsd_namespace=XSD_NAMESPACE) 
 """It opens a template file, and it loads all lines to a string variable and returns string. Template object includes the variable. Limitation of a file size isn't needed there.""" 
 try: parser = OptionParser() parser.add_option( "-v", "--verbose", dest="verbose", action="store_true", help="display more about what is going on") (options, args) = parser.parse_args() if options.verbose: isc.log.init("b10-stats-httpd", "DEBUG", 99) stats_httpd = StatsHttpd() stats_httpd.start() except OptionValueError as ove: logger.fatal(STATHTTPD_BAD_OPTION_VALUE, ove) sys.exit(1) except isc.cc.session.SessionError as se: logger.fatal(STATHTTPD_CC_SESSION_ERROR, se) sys.exit(1) except HttpServerError as hse: logger.fatal(STATHTTPD_START_SERVER_INIT_ERROR, hse) sys.exit(1) except KeyboardInterrupt as kie: logger.info(STATHTTPD_STOPPED_BY_KEYBOARD)  |