source: genesis/nodes/make-map.py@ 8306

Last change on this file since 8306 was 8306, checked in by rick, 14 years ago

Small typo fix.
[found by Richard]

  • Property svn:executable set to *
File size: 6.7 KB
Line 
1#!/usr/bin/env python
2# vim:ts=2:et:sw=2:ai
3#
4# Build topological network graph
5# Rick van der Zwet <info@rickvanderzwet.nl>
6
7import cgi
8import gformat
9import re
10import sys
11import urllib
12import yaml
13import math
14
15def get_yaml(gfile):
16 """ Get configuration yaml for 'item'"""
17 f = open(gfile, 'r')
18 datadump = yaml.load(f)
19 return datadump
20
21def write_yaml(gfile, datadump):
22 """ Write configuration yaml for 'item'"""
23 f = open(gfile, 'w')
24 f.write(yaml.dump(datadump, default_flow_style=False))
25 f.close()
26
27CACHE_FILE = '/tmp/rd2etrs.yaml'
28coordinates = None
29
30def etrs2rd(lam, phi):
31 """ Convert rd to etrs """
32
33 item = dict()
34 (remainder, item['lam_deg']) = math.modf(lam)
35 remainder *= 60
36 (remainder, item['lam_min']) = math.modf(remainder)
37 item['lam_sec'] = remainder * 60
38
39 (remainder, item['phi_deg']) = math.modf(phi)
40 remainder *= 60
41 (remainder, item['phi_min']) = math.modf(remainder)
42 item['phi_sec'] = remainder * 60
43
44 item['func'] = 'etrs2rd'
45
46 args = "&".join(["%s=%s" % (k,v) for k,v in item.iteritems()])
47 url = 'http://www.rdnap.nl/cgi-bin/rdetrs.pl?%s' % args
48 print "### Fetching coordinate %s, %s using: %s" % (phi, lam, url)
49 f = urllib.urlopen(url)
50 raw = f.read()
51
52 r = re.compile('name="([a-z_]+)" value="([0-9\.]+)"')
53 for i in r.finditer(raw):
54 name, value = i.group(1,2)
55 value = float(value)
56 item[name] = value
57 return (item['xrd'], item['yrd'])
58
59
60def rd2etrs(xrd, yrd, hnap=0.0):
61 """ Convert rd to etrs """
62 # Get cache is exists
63 global coordinates
64 if coordinates == None:
65 try:
66 coordinates = get_yaml(CACHE_FILE)
67 except (IOError,AttributeError):
68 coordinates = dict()
69 pass
70
71 # Check if item in cache
72 xrd = float(str(xrd))
73 yrd = float(str(yrd))
74 if coordinates.has_key((xrd, yrd)):
75 return coordinates[(xrd, yrd)]
76
77 # Get new coordinate
78 item = dict()
79 item['xrd'] = xrd
80 item['yrd'] = yrd
81 item['hnap'] = hnap
82 item['func'] = 'rd2etrs'
83 args = "&".join(["%s=%s" % (k,v) for k,v in item.iteritems()])
84 url = 'http://www.rdnap.nl/cgi-bin/rdetrs.pl?%s' % args
85 print "### Not in Cache, Fetching coordinate %s, %s from %s" % (xrd, yrd, url)
86 f = urllib.urlopen(url)
87 raw = f.read()
88
89 r = re.compile('name="([a-z_]+)" value="([0-9\.]+)"')
90 for i in r.finditer(raw):
91 name, value = i.group(1,2)
92 value = float(value)
93 item[name] = value
94
95 lam = item['lam_deg'] + (item['lam_min'] + (item['lam_sec'] / 60)) / 60
96 phi = item['phi_deg'] + (item['phi_min'] + (item['phi_sec'] / 60)) / 60
97 coordinates[(xrd, yrd)] = (lam, phi)
98 write_yaml(CACHE_FILE, coordinates)
99 return (lam, phi)
100
101def make_graph():
102 f = open('kmlfile.kml', 'w')
103 f.write("""<?xml version="1.0" encoding="UTF-8"?>
104<kml xmlns="http://earth.google.com/kml/2.0">
105 <Document>
106 <name>WirelessLeiden Nodemap</name>
107 <open>1</open>
108 <description>Generated realtime status of all Wireless Leiden AccessPoints</description>
109 <Style id="node_status_up">
110 <IconStyle>
111 <scale>0.5</scale>
112 <Icon><href>http://www.google.com/mapfiles/kml/paddle/grn-stars-lv.png</href></Icon>
113 </IconStyle>
114 </Style>
115 <Style id="node_status_down">
116 <IconStyle>
117 <scale>0.5</scale>
118 <Icon><href>http://www.google.com/mapfiles/kml/paddle/red-stars-lv.png</href></Icon>
119 </IconStyle>
120 </Style>
121 <Style id="node_status_planned">
122 <IconStyle>
123 <scale>0.5</scale>
124 <Icon><href>http://www.google.com/mapfiles/kml/paddle/wht-stars-lv.png</href></Icon>
125 </IconStyle>
126 </Style>
127 <Folder>
128 <name>Nodes</name>
129 <visibility>0</visibility>
130 <description>All active nodes and links</description>
131 """)
132
133 poel = {}
134 link_type = {}
135 node = {}
136
137 nodes = []
138 links = []
139 try:
140 for host in gformat.get_hostlist():
141 print "## Processing host", host
142 datadump = gformat.get_yaml(host)
143 iface_keys = [elem for elem in datadump.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
144 for iface_key in iface_keys:
145 l = datadump[iface_key]['ip']
146 addr, mask = l.split('/')
147
148 addr = gformat.parseaddr(addr)
149 mask = int(mask)
150 addr = addr & ~((1 << (32 - mask)) - 1)
151 if poel.has_key(addr):
152 poel[addr] += [host]
153 else:
154 poel[addr] = [host]
155 # Assume all eth2wifibridge to be 11a for a moment
156 iface_parent = '_'.join(iface_key.split('_')[0:2])
157 if datadump[iface_parent].has_key('extra_type') and datadump[iface_parent]['extra_type'] == 'eth2wifibridge':
158 link_type[addr] = '11a'
159 else:
160 link_type[addr] = datadump[iface_parent]['type']
161 print "### %s [%s] is of type %s" % (gformat.showaddr(addr), iface_key, link_type[addr])
162 lam, phi = rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
163 node[host] = (lam, phi)
164 f.write("""
165 <description>All active nodes</description>
166 <Placemark>
167 <name>Node %(name)s</name>
168 <description>%(desc)s</description>
169 <styleUrl>#node_status_up</styleUrl>
170 <Point><coordinates>%(lam)s,%(phi)s,0</coordinates></Point>
171 </Placemark>
172 """ % {'name' : host, 'desc' : cgi.escape(datadump['location']), 'lam' : lam, 'phi' : phi})
173 nodes += [("POINT(%s, %s)" % (lam, phi))]
174 except (KeyError, ValueError), e:
175 print "[FOUT] in '%s' interface '%s'" % (host,iface_key)
176 raise
177 sys.exit(1)
178
179 f.write("""
180 </Folder>
181 <Folder>
182 <name>Links</name>
183 <visibility>0</visibility>
184 <description>All links</description>
185 """)
186 for addr,leden in poel.iteritems():
187 if link_type[addr] == '11a':
188 color = '#ff0000ff'
189 weight = 2
190 elif link_type[addr] == 'eth':
191 color = '#ffff0000'
192 weight = 4
193 else:
194 color = '#ff000000'
195 weight = 1
196
197 leden = sorted(set(leden))
198 for index,lid in enumerate(leden[:-1]):
199 for buur in leden[index + 1:]:
200 f.write("""
201 <Placemark>
202 <name>%(name)s</name>
203 <visibility>0</visibility>
204 <description>%(desc)s</description>
205 <LineString>
206 <tessellate>0</tessellate>
207 <coordinates> %(lam1)s, %(phi1)s, 0
208 %(lam2)s , %(phi2)s, 0 </coordinates>
209 </LineString>
210 <Style>%(style)s</Style>
211 </Placemark>
212 """ % { 'lam1' : node[lid][0],
213 'phi1' : node[lid][1],
214 'lam2' : node[buur][0],
215 'phi2' : node[buur][1],
216 'name' : "Interlink: %s --- %s" % (lid, buur),
217 'desc' : "%s [%s]" % (gformat.showaddr(addr), link_type[addr]),
218 'style' : "<LineStyle><color>%s</color><width>%s</width></LineStyle>" % (color, weight),
219 })
220 f.write("""
221 </Folder>
222 </Document>
223</kml>
224 """)
225 f.close()
226
227
228if __name__ == "__main__":
229 make_graph()
230
Note: See TracBrowser for help on using the repository browser.