Changeset 8267 in genesis


Ignore:
Timestamp:
Aug 8, 2010, 3:21:43 PM (15 years ago)
Author:
rick
Message:
  • Allow to be library
  • Allow cgitb debugging
  • Output proper yaml code
File:
1 edited

Legend:

Unmodified
Added
Removed
  • nodes/gformat.py

    r8262 r8267  
    55# Rick van der Zwet <info@rickvanderzwet.nl>
    66import cgi
     7import cgitb
     8import copy
    79import glob
    810import os
     
    1719__version__ = '$Id$'
    1820
     21
    1922files = [
    2023    'authorized_keys',
     
    2730
    2831
    29 def print_title(nodelist):
     32def get_proxylist():
     33  """Get all available proxies proxyX sorting based on X number"""
     34  os.chdir(NODE_DIR)
     35  proxylist = sorted(glob.glob("proxy*"),
     36                key=lambda name: int(''.join([c for c in name if c in string.digits])),
     37                cmp=lambda x,y: x - y)
     38  return proxylist
     39
     40
     41
     42def get_nodelist():
     43  """ Get all available nodes - sorted """
     44  os.chdir(NODE_DIR)
     45  nodelist = sorted(glob.glob("CNode*"))
     46  return nodelist
     47
     48
     49
     50def generate_title(nodelist):
    3051  """ Main overview page """
    3152  items = {'root' : "." }
    32   print """
     53  output = """
    3354<html>
    3455  <head>
     
    5374  for node in sorted(nodelist):
    5475    items['node'] = node
    55     print '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
     76    output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
    5677    for config in files:
    5778      items['config'] = config
    58       print '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
    59     print "</tr>"
    60   print """
     79      output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
     80    output += "</tr>"
     81  output += """
    6182    </table>
    6283    <hr />
     
    6788  """ % __version__
    6889
    69 
    70 
    71 def print_node(node):
     90  return output
     91
     92
     93
     94def generate_node(node):
    7295  """ Print overview of all files available for node """
    73   print "\n".join(files)
     96  return "\n".join(files)
    7497
    7598
     
    249272
    250273
     274def write_yaml(item, datadump):
     275  """ Write configuration yaml for 'item'"""
     276  gfile = NODE_DIR + '/%s/wleiden.yaml' % item
     277
     278  f = open(gfile, 'w')
     279  f.write(format_wleiden_yaml(datadump))
     280  f.close()
     281
     282
     283
    251284def generate_resolv_conf(datadump):
    252285  """ Generate configuration file '/etc/resolv.conf' """
     
    261294""" % datadump
    262295 
    263   # proxyX sorting based on X number
    264   os.chdir(NODE_DIR)
    265   proxies = sorted(glob.glob("proxy*"),
    266               key=lambda name: int(''.join([c for c in name if c in string.digits])),
    267               cmp=lambda x,y: x - y)
    268 
    269   for proxy in proxies:
     296  for proxy in get_proxylist():
    270297    proxy_ip = get_yaml(proxy)['masterip']
    271298    output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
     
    274301
    275302
    276 def generate_wleiden_yaml(datadump):
     303def format_yaml_value(value):
     304  """ Get yaml value in right syntax for outputting """
     305  if isinstance(value,str):
     306    output = "'%s'" % value
     307  else:
     308    output = value
     309  return output
     310
     311
     312
     313def format_wleiden_yaml(datadump):
    277314  """ Special formatting to ensure it is editable"""
    278   output = generate_header("#")
    279   output += "# Genesis config yaml style\n"
     315  output = "# Genesis config yaml style\n"
    280316  output += "# vim:ts=2:et:sw=2:ai\n"
    281317  output += "#\n"
    282318  iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
    283319  for key in sorted(set(datadump.keys()) - set(iface_keys)):
    284     output += "%s: %s\n" % (key, datadump[key])
     320    output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
    285321 
    286322  output += "\n\n"
     
    289325    output += "%s:\n" % iface_key
    290326    for key in sorted(datadump[iface_key]):
    291       #output += yaml.dump(datadump[iface_key], default_flow_style=False)
    292       output += "  %s: %s\n" % (key, datadump[iface_key][key])
     327      output += "  %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
    293328    output += "\n\n"
    294329
     
    297332
    298333
    299 def print_config(node, config):
     334def generate_wleiden_yaml(datadump):
     335  """ Generate (petty) version of wleiden.yaml"""
     336  output = generate_header("#")
     337  output += format_wleiden_yaml(datadump)
     338  return output
     339
     340
     341
     342def generate_config(node, config):
    300343  """ Print configuration file 'config' of 'node' """
     344  output = ""
    301345  try:
    302346    # Load config file
    303347    datadump = get_yaml(node)
    304348   
     349    # Preformat certain needed variables for formatting and push those into special object
     350    datadump_extra = copy.deepcopy(datadump)
     351    if not datadump_extra.has_key('domain'):
     352      datadump_extra['domain'] = 'wleiden.net'
     353    datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
     354    datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
     355
    305356    if config == 'wleiden.yaml':
    306       print generate_wleiden_yaml(datadump)
    307       return
    308 
    309     # Preformat certain needed variables for formatting
    310     if not datadump.has_key('domain'):
    311       datadump['domain'] = 'wleiden.net'
    312     datadump['nodename_lower'] = datadump['nodename'].lower()
    313     datadump['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
    314 
    315     if config == 'authorized_keys':
     357      output += generate_wleiden_yaml(datadump)
     358    elif config == 'authorized_keys':
    316359      f = open("global_keys", 'r')
    317       print f.read()
     360      output += f.read()
    318361      f.close()
    319362    elif config == 'dnsmasq.conf':
    320       print generate_dnsmasq_conf(datadump)
     363      output += generate_dnsmasq_conf(datadump_extra)
    321364    elif config == 'rc.conf.local':
    322       print generate_rc_conf_local(datadump)
     365      output += generate_rc_conf_local(datadump_extra)
    323366    elif config == 'resolv.conf':
    324       print generate_resolv_conf(datadump)
     367      output += generate_resolv_conf(datadump_extra)
    325368    else:
    326369      assert False, "Config not found!"   
    327370  except IOError, e:
    328     print "[ERROR] Config file not found"
     371    output += "[ERROR] Config file not found"
     372  return output
    329373
    330374
     
    342386    sys.exit(0)
    343387 
    344   os.chdir(NODE_DIR)
    345   nodelist = glob.glob("CNode*")
    346388 
    347389  uri = os.environ['PATH_INFO'].strip('/').split('/')
     390  output = ""
    348391  if not uri[0]:
    349     print "Content-type:text/html\r\n\r\n",
    350     print_title(nodelist)
     392    output += "Content-type:text/html\r\n\r\n"
     393    output += generate_title(get_nodelist())
    351394  elif len(uri) == 1:
    352     print "Content-type:text/plain\r\n\r\n",
    353     print_node(uri[0])
     395    output += "Content-type:text/plain\r\n\r\n"
     396    output += generate_node(uri[0])
    354397  elif len(uri) == 2:
    355     print "Content-type:text/plain\r\n\r\n",
    356     print_config(uri[0], uri[1])
     398    output += "Content-type:text/plain\r\n\r\n"
     399    output += generate_config(uri[0], uri[1])
    357400  else:
    358401    assert False, "Invalid option"
    359 
     402  print output
    360403
    361404
     
    371414
    372415
    373 # Allow easy hacking using the CLI
    374 if not os.environ.has_key('PATH_INFO'):
    375   if len(sys.argv) < 2:
    376     usage()
    377 
    378   if sys.argv[1] == "standalone":
    379     import SocketServer
    380     import CGIHTTPServer
    381     try:
    382       PORT = int(sys.argv[2])
    383     except (IndexError,ValueError):
    384       PORT = 8000
    385 
    386     class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
    387       """ Serve this CGI from the root of the webserver """
    388       def is_cgi(self):
    389         if "favicon" in self.path:
    390           return False
    391 
    392         self.cgi_info = (__file__, self.path)
    393         self.path = ''
    394         return True
    395     handler = MyCGIHTTPRequestHandler
    396     httpd = SocketServer.TCPServer(("", PORT), handler)
    397     httpd.server_name = 'localhost'
    398     httpd.server_port = PORT
     416def main():
     417  """Hard working sub"""
     418  # Allow easy hacking using the CLI
     419  if not os.environ.has_key('PATH_INFO'):
     420    if len(sys.argv) < 2:
     421      usage()
     422 
     423    if sys.argv[1] == "standalone":
     424      import SocketServer
     425      import CGIHTTPServer
     426      try:
     427        PORT = int(sys.argv[2])
     428      except (IndexError,ValueError):
     429        PORT = 8000
     430 
     431      class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
     432        """ Serve this CGI from the root of the webserver """
     433        def is_cgi(self):
     434          if "favicon" in self.path:
     435            return False
     436 
     437          self.cgi_info = (__file__, self.path)
     438          self.path = ''
     439          return True
     440      handler = MyCGIHTTPRequestHandler
     441      httpd = SocketServer.TCPServer(("", PORT), handler)
     442      httpd.server_name = 'localhost'
     443      httpd.server_port = PORT
     444     
     445      print "serving at port", PORT
     446      httpd.serve_forever()
     447    elif sys.argv[1] == "test":
     448      os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
     449      os.environ['SCRIPT_NAME'] = __file__
     450      process_cgi_request()
     451    else:
     452      usage()
     453  else:
     454    cgitb.enable()
     455    process_cgi_request()
    399456   
    400     print "serving at port", PORT
    401     httpd.serve_forever()
    402   elif sys.argv[1] == "test":
    403     os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
    404     os.environ['SCRIPT_NAME'] = __file__
    405     process_cgi_request()
    406   else:
    407     usage()
    408 else:
    409   process_cgi_request()
     457
     458if __name__ == "__main__":
     459  main()
Note: See TracChangeset for help on using the changeset viewer.