Changeset 9283 in genesis for tools/gformat.py


Ignore:
Timestamp:
Jun 23, 2011, 6:33:00 PM (13 years ago)
Author:
rick
Message:

Get rid of to many whitespace.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • tools/gformat.py

    r8948 r9283  
    3333    from yaml import Loader, Dumper
    3434
    35  
     35
    3636
    3737if os.environ.has_key('CONFIGROOT'):
    3838  NODE_DIR = os.environ['CONFIGROOT']
    3939else:
    40   NODE_DIR = os.path.dirname(__file__) + '/../nodes'
     40  NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
    4141__version__ = '$Id$'
    4242
    4343
    44 files = [ 
     44files = [
    4545    'authorized_keys',
    4646    'dnsmasq.conf',
     
    8282
    8383def angle_between_points(lat1,lat2,long1,long2):
    84   """ 
     84  """
    8585  Return Angle in radians between two GPS coordinates
    8686  See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
     
    103103  if degrees < p:
    104104    return "n"
    105   elif degrees < (90 - p): 
     105  elif degrees < (90 - p):
    106106    return "no"
    107   elif degrees < (90 + p): 
     107  elif degrees < (90 + p):
    108108    return "o"
    109   elif degrees < (180 - p): 
     109  elif degrees < (180 - p):
    110110    return "zo"
    111   elif degrees < (180 + p): 
     111  elif degrees < (180 + p):
    112112    return "z"
    113   elif degrees < (270 - p): 
     113  elif degrees < (270 - p):
    114114    return "zw"
    115   elif degrees < (270 + p): 
     115  elif degrees < (270 + p):
    116116    return "w"
    117   elif degrees < (360 - p): 
     117  elif degrees < (360 - p):
    118118    return "nw"
    119119  else:
     
    123123def generate_title(nodelist):
    124124  """ Main overview page """
    125   items = {'root' : "." } 
     125  items = {'root' : "." }
    126126  output = """
    127127<html>
     
    173173def generate_header(ctag="#"):
    174174  return """\
    175 %(ctag)s 
     175%(ctag)s
    176176%(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
    177177%(ctag)s Generated at %(date)s by %(host)s
    178 %(ctag)s 
     178%(ctag)s
    179179""" % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
    180180
     
    204204  ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
    205205  return ip_addr == ip_canidate
    206  
     206
    207207
    208208
     
    218218  output = generate_header()
    219219  output += """\
    220 # DHCP server options 
     220# DHCP server options
    221221dhcp-authoritative
    222222dhcp-fqdn
     
    246246    datadump[iface_key]['dhcp_stop'] =  dhcp_part + "." + dhcp_stop
    247247    output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(subnet)s,24h\n\n" % datadump[iface_key]
    248  
     248
    249249  return output
    250250
     
    256256  output += """\
    257257hostname='%(nodetype)s%(nodename)s.%(domain)s'
    258 location='%(location)s' 
     258location='%(location)s'
    259259""" % datadump
    260  
     260
    261261  # TProxy configuration
    262262  output += "\n"
     
    269269  except KeyError:
    270270    output += "tproxy_enable='NO'\n"
    271  
     271
    272272  output += '\n'
    273273  # lo0 configuration:
    274274  # - 172.32.255.1/32 is the proxy.wleiden.net deflector
    275   # - masterip is special as it needs to be assigned to at 
     275  # - masterip is special as it needs to be assigned to at
    276276  #   least one interface, so if not used assign to lo0
    277277  addrs_list = { 'lo0' : ["127.0.0.1/8", "172.31.255.1/32"] }
    278   iface_map = {'lo0' : 'lo0'} 
     278  iface_map = {'lo0' : 'lo0'}
    279279
    280280  masterip_used = False
     
    283283      masterip_used = True
    284284      break
    285   if not masterip_used: 
     285  if not masterip_used:
    286286    addrs_list['lo0'].append(datadump['masterip'] + "/32")
    287287
     
    307307    if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
    308308      # Create wlanX interface
    309       ifacedump['wlanif'] ="wlan%i" % wlan_count 
     309      ifacedump['wlanif'] ="wlan%i" % wlan_count
    310310      iface_map[interface] = ifacedump['wlanif']
    311311      wlan_count += 1
     
    318318      ifacedump['mode'] = '11b'
    319319      if ifacedump['type'] in ['11a', '11b' '11g']:
    320         ifacedump['mode'] = ifacedump['type'] 
     320        ifacedump['mode'] = ifacedump['type']
    321321
    322322      if not ifacedump.has_key('channel'):
     
    333333      output += ("create_args_%(wlanif)s='wlanmode %(wlanmode)s mode " +\
    334334        "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
    335        
     335
    336336    elif ifacedump['type'] in ['ethernet', 'eth']:
    337337      # No special config needed besides IP
     
    340340      assert False, "Unknown type " + ifacedump['type']
    341341
    342   # Print IP address which needs to be assigned over here 
     342  # Print IP address which needs to be assigned over here
    343343  output += "\n"
    344344  for iface,addrs in sorted(addrs_list.iteritems()):
     
    418418nameserver 127.0.0.1
    419419
    420 # Proxies are recursive nameservers 
     420# Proxies are recursive nameservers
    421421# needs to be in resolv.conf for dnsmasq as well
    422422""" % datadump
    423  
     423
    424424  for proxy in get_proxylist():
    425425    proxy_ip = get_yaml(proxy)['masterip']
     
    435435  else:
    436436    output = value
    437   return output 
     437  return output
    438438
    439439
     
    441441def format_wleiden_yaml(datadump):
    442442  """ Special formatting to ensure it is editable"""
    443   output = "# Genesis config yaml style\n" 
     443  output = "# Genesis config yaml style\n"
    444444  output += "# vim:ts=2:et:sw=2:ai\n"
    445445  output += "#\n"
     
    447447  for key in sorted(set(datadump.keys()) - set(iface_keys)):
    448448    output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
    449  
     449
    450450  output += "\n\n"
    451  
     451
    452452  key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
    453453    'extra_type', 'channel', 'ssid', 'dhcp' ]
     
    457457    for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
    458458      if datadump[iface_key].has_key(key):
    459         output += "  %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key])) 
     459        output += "  %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
    460460    output += "\n\n"
    461461
     
    473473def generate_yaml(datadump):
    474474  return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
    475  
     475
    476476
    477477
     
    483483    if datadump == None:
    484484      datadump = get_yaml(node)
    485    
     485
    486486    # Preformat certain needed variables for formatting and push those into special object
    487487    datadump_extra = copy.deepcopy(datadump)
     
    504504      output += generate_resolv_conf(datadump_extra)
    505505    else:
    506       assert False, "Config not found!"   
     506      assert False, "Config not found!"
    507507  except IOError, e:
    508508    output += "[ERROR] Config file not found"
     
    522522    print "[INFO] All done, redirecting in 5 seconds"
    523523    sys.exit(0)
    524  
    525  
     524
     525
    526526  uri = os.environ['PATH_INFO'].strip('/').split('/')
    527527  output = ""
     
    547547    fqdn = datadump['nodetype'] + datadump['nodename']
    548548  return(fqdn)
    549  
    550  
     549
     550
    551551
    552552def make_dns():
     
    560560  for node in get_hostlist():
    561561    datadump = get_yaml(node)
    562  
     562
    563563    # Proxy naming convention is special
    564564    fqdn = get_fqdn(datadump)
     
    585585        netmask = int(netmask)
    586586        addr = addr & ~((1 << (32 - netmask)) - 1)
    587         if pool.has_key(addr): 
     587        if pool.has_key(addr):
    588588          pool[addr] += [(iface_name, fqdn, ip)]
    589         else: 
     589        else:
    590590          pool[addr] = [(iface_name, fqdn, ip)]
    591591        continue
     
    604604      pool_members = [k[1] for k in value]
    605605      for item in value:
    606         (iface_name, fqdn, ip) = item 
     606        (iface_name, fqdn, ip) = item
    607607        pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + "-".join(sorted(list(set(pool_members) - set([fqdn]))))
    608608        wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
     
    622622      else:
    623623        wleiden_cname[k] = v
    624      
     624
    625625  details = dict()
    626626  # 24 updates a day allowed
     
    635635  \n'''
    636636
    637    
     637
    638638  if not os.path.isdir('dns'):
    639639    os.makedirs('dns')
     
    644644  for host,ip in wleiden_zone.iteritems():
    645645    if valid_addr(ip):
    646       f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip)) 
     646      f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
    647647  for source,dest in wleiden_cname.iteritems():
    648648    f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
    649649  f.close()
    650  
     650
    651651  # Create whole bunch of specific sub arpa zones. To keep it compliant
    652652  for s in range(16,32):
     
    661661        if int(ip.split('.')[1]) == s:
    662662          rev_ip = '.'.join(reversed(ip.split('.')))
    663           f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower())) 
     663          f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
    664664    f.close()
    665665
     
    672672\tstatic                       =  Generate all config files and store on disk
    673673\t                                with format ./static/%%NODE%%/%%FILE%%
    674 \ttest CNodeRick dnsmasq.conf  =  Receive output of CGI script 
     674\ttest CNodeRick dnsmasq.conf  =  Receive output of CGI script
    675675\t                                for arguments CNodeRick/dnsmasq.conf
    676676"""
     
    685685    if len(sys.argv) < 2:
    686686      usage()
    687  
     687
    688688    if sys.argv[1] == "standalone":
    689689      import SocketServer
     
    695695      except (IndexError,ValueError):
    696696        PORT = 8000
    697  
     697
    698698      class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
    699699        """ Serve this CGI from the root of the webserver """
     
    701701          if "favicon" in self.path:
    702702            return False
    703  
     703
    704704          self.cgi_info = (__file__, self.path)
    705705          self.path = ''
     
    709709      httpd.server_name = 'localhost'
    710710      httpd.server_port = PORT
    711      
     711
    712712      print "serving at port", PORT
    713713      try:
     
    735735    elif sys.argv[1] == "dns":
    736736      make_dns()
    737     elif sys.argv[1] == "cleanup":   
     737    elif sys.argv[1] == "cleanup":
    738738      # First generate all datadumps
    739739      datadumps = dict()
     
    741741        datadump = get_yaml(host)
    742742        datadumps[get_fqdn(datadump)] = datadump
    743      
     743
    744744        datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
    745745        write_yaml(host, datadump)
    746     else:                             
    747       usage()                         
    748   else:                               
    749     cgitb.enable()                   
    750     process_cgi_request()             
    751                                      
    752                                  
    753 if __name__ == "__main__":           
    754   main()                             
     746    else:
     747      usage()
     748  else:
     749    cgitb.enable()
     750    process_cgi_request()
     751
     752
     753if __name__ == "__main__":
     754  main()
Note: See TracChangeset for help on using the changeset viewer.