Share Pastebin
Guest
Public paste!

Status server

By: a guest | Jul 15th, 2010 | Syntax: Python | Size: 4.89 KB | Hits: 297 | Expires: Never
Copy text to clipboard
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """Basic Status HTTP Server
  4.  
  5. Simple implementation of Python's BaseHTTPServer
  6. that creates a web server which prints out
  7. basic system information in plain text, HTML or JSON.
  8.  
  9. :Author
  10.    Andrés Gattinoni <andresgattinoni@gmail.com>
  11.  
  12. :Website
  13.    http://www.tail-f.com.ar
  14.  
  15. :Version
  16.    0.1
  17. """
  18. import os
  19. import sys
  20. import time
  21. import json
  22. import BaseHTTPServer
  23. from optparse import OptionParser
  24. from urlparse import urlparse
  25.  
  26. __author__ = "Andrés Gattinoni <andresgattinoni@gmail.com>"
  27. __version__ = "StatusServer/0.1"
  28.  
  29. class RequestHandler (BaseHTTPServer.BaseHTTPRequestHandler):
  30.     """Request handler
  31.  
  32.    Handles HTTP GET requests and returns
  33.    basic system information in different formats"""
  34.  
  35.     server_version = __version__
  36.    
  37.     def do_GET (self):
  38.         """Handles GET requests"""
  39.         args = urlparse(self.path)
  40.         self.send_response(200)
  41.         body = self._get_status(args.path[1:])
  42.         self.end_headers()
  43.         self.wfile.write(body)
  44.         return
  45.  
  46.     def _get_data (self):
  47.         """Gathers basic system information"""
  48.         return {'platform': sys.platform,
  49.                 'os_name': ' '.join(os.uname()),
  50.                 'loadavg': "%01.2f, %01.2f, %01.2f" % \
  51.                            os.getloadavg(),
  52.                 'date': time.strftime('%a %b %d %H:%M:%S %Z %Y', \
  53.                                       time.localtime()),
  54.                 'pyver': 'Python %s' % sys.version}
  55.  
  56.     def _get_plain (self):
  57.         """Returns the system info in plain text format"""
  58.         self.send_header('Content-Type', \
  59.                          'text/plain; charset=utf-8')
  60.         data = self._get_data()
  61.         return "System Status:\n" \
  62.                "--------------\n" \
  63.                "Platform: %s\n" \
  64.                "OS: %s\n" \
  65.                "System date: %s\n" \
  66.                "Load average: %s\n"  \
  67.                "Python version: %s\n" % \
  68.                (data['platform'], \
  69.                 data['os_name'], \
  70.                 data['date'], \
  71.                 data['loadavg'], \
  72.                 data['pyver'])
  73.  
  74.     def _get_json (self):
  75.         """Returns the system info as a json string"""
  76.         self.send_header('Content-Type', \
  77.                          'application/json; charset=utf-8')
  78.         return json.dumps(self._get_data())
  79.  
  80.     def _get_html (self):
  81.         """Returns the system info as an HTML document"""
  82.         self.send_header('Content-Type', \
  83.                          'text/html; charset=utf-8')
  84.         data = self._get_data()
  85.         return "<html>" \
  86.                "<head>" \
  87.                "<title>System status</title>" \
  88.                "</head>" \
  89.                "<body>" \
  90.                "<h1>System status</h1>" \
  91.                "<ul>" \
  92.                "    <li><strong>Platform:</strong> %s</li>" \
  93.                "    <li><strong>OS Name:</strong> %s</li>" \
  94.                "    <li><strong>System date:</strong> %s</li>" \
  95.                "    <li><strong>Load average:</strong> %s</li>" \
  96.                "    <li><strong>Python version:</strong> %s</li>" \
  97.                "</ul>" \
  98.                "</body>" \
  99.                "</html>" % \
  100.                (data['platform'], \
  101.                 data['os_name'], \
  102.                 data['date'], \
  103.                 data['loadavg'], \
  104.                 data['pyver'])
  105.  
  106.     def _get_status (self, format):
  107.         """Returns the status string
  108.           in the appropriate format"""
  109.         if format == 'plain':
  110.             return self._get_plain()
  111.         elif format == 'json':
  112.             return self._get_json()
  113.         else:
  114.             return self._get_html()
  115.            
  116.  
  117. def main ():
  118.     """Main function of the script
  119.       Runs the HTTP Server
  120.       """
  121.     parser = OptionParser(usage="%prog [options]", \
  122.                           version=__version__,
  123.                           description="Basic HTTP Server which provides " \
  124.                                       "general information of the system status")
  125.     parser.add_option('-a', '--address', dest='host', \
  126.                       help='Host/IP address to bind to', \
  127.                       metavar='ADDRESS', default='localhost')
  128.     parser.add_option('-p', '--port', dest='port', \
  129.                       help='Port to bind to', \
  130.                       metavar='PORT', default=8000, \
  131.                       type='int')
  132.     (option, args) = parser.parse_args()
  133.  
  134.     if option.port < 0:
  135.         parser.error("Port number must be a positive integer")
  136.         return 1
  137.  
  138.     if option.port < 1024:
  139.         print "Warning: ports lower than 1024 are reserved to root"
  140.  
  141.     try:
  142.         httpd = BaseHTTPServer.HTTPServer((option.host, option.port), RequestHandler)
  143.         httpd.serve_forever()
  144.     except KeyboardInterrupt:
  145.         print "Shutting down."
  146.     return 0
  147.  
  148. if __name__ == "__main__":
  149.     sys.exit(main())