source: genesis/tools/make_network_kml.py@ 11444

Last change on this file since 11444 was 11444, checked in by rick, 12 years ago

Quick om export te maken van nodeplanner applicatie.

  • Property svn:executable set to *
File size: 5.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>
6import gformat
7import glob
8import json
9import os
10import re
11import subprocess
12import sys
13import tempfile
14import yaml
15
16
17try:
18 store = yaml.load(open('store.yaml','r'))
19except IOError:
20 store = None
21
22
23HEADER = '''<?xml version="1.0" encoding="UTF-8"?>
24<kml xmlns="http://www.opengis.net/kml/2.2">
25<Document>
26 <Style id="linkDown">
27 <LineStyle>
28 <color>990000ff</color>
29 <width>2</width>
30 </LineStyle>
31 </Style>
32 <Style id="linkUp">
33 <LineStyle>
34 <color>9900ff00</color>
35 <width>3</width>
36 </LineStyle>
37 </Style>
38 <Style id="linkPlanned">
39 <LineStyle>
40 <color>99ff0000</color>
41 <width>1</width>
42 </LineStyle>
43 </Style>
44
45'''
46
47POINT = '''
48 <Placemark>
49 <name>%(nodename)s</name>
50 <description>%(nodename)s</description>
51 <Point>
52 <coordinates>%(longitude)s,%(latitude)s,0</coordinates>
53 </Point>
54 </Placemark>
55'''
56
57LINE = '''
58 <Placemark>
59 <styleUrl>#%(styleId)s</styleUrl>
60 <LineString>
61 <coordinates>
62 %(longitudeA)s,%(latitudeA)s,0
63 %(longitudeB)s,%(latitudeB)s,0
64 </coordinates>
65 </LineString>
66 </Placemark>
67'''
68
69FOOTER = '''
70</Document>
71</kml>
72'''
73
74def get_graph_data(debug=False):
75 poel = {}
76 link_type = {}
77 link_data = {}
78 link_status = {}
79 hosts = {}
80
81 try:
82 for host in gformat.get_hostlist():
83 if debug: print "## Processing host", host
84 datadump = gformat.get_yaml(host)
85 nodename = datadump['nodename']
86 hosts[nodename] = datadump
87
88 for iface_key in datadump['autogen_iface_keys']:
89 l = datadump[iface_key]['ip']
90 addr, mask = l.split('/')
91
92 # Not parsing of these folks please
93 if not gformat.valid_addr(addr):
94 continue
95
96 addr = gformat.parseaddr(addr)
97 mask = int(mask)
98 addr = addr & ~((1 << (32 - mask)) - 1)
99 if poel.has_key(addr):
100 poel[addr] += [nodename]
101 if link_status[addr] == 'linkUp':
102 if datadump['status'] == 'planned':
103 link_status[addr] = 'linkPlanned'
104 elif datadump[iface_key]['status'] == 'planned':
105 link_status[addr] = 'linkPlanned'
106 elif datadump[iface_key]['status'] == 'down':
107 link_status[addr] = 'linkDown'
108 else:
109 poel[addr] = [nodename]
110 # Assume all ns_ip to be 11a for a moment
111 if datadump[iface_key].has_key('ns_ip'):
112 link_type[addr] = '11a'
113 else:
114 link_type[addr] = datadump[iface_key]['type']
115
116 if datadump['status'] == 'planned':
117 link_status[addr] = 'linkPlanned'
118 elif datadump[iface_key]['status'] == 'planned':
119 link_status[addr] = 'linkPlanned'
120 elif datadump[iface_key]['status'] == 'down':
121 link_status[addr] = 'linkDown'
122 else:
123 link_status[addr] = 'linkUp'
124
125 link_data[addr] = 1
126 iface = datadump[iface_key]['autogen_ifname']
127 nodename = datadump['nodename']
128 INTERVAL = 60 * 10
129 if store and store['uptime'].has_key(nodename) and store['snmp'].has_key(nodename) and store['traffic'].has_key(nodename):
130 if store and store['traffic'][nodename].has_key(iface):
131 (b_in, b_out) = store['traffic'][nodename][iface]
132 uptime = store['uptime'][nodename]
133 t_kb = float(b_in + b_out) / 1024
134 if debug: print "# INFO: Found %s kB in %s seconds" % (t_kb, INTERVAL)
135 retval = ((t_kb) / uptime) * INTERVAL
136 link_data[addr] = retval
137
138 if debug: print "### %s [%s] is of type %s" % (gformat.showaddr(addr), iface_key, link_type[addr])
139 except (KeyError, ValueError), e:
140 if debug: print "[FOUT] in '%s' interface '%s'" % (host,iface_key)
141 if debug: print e
142 sys.exit(1)
143 return (poel, link_type, link_data, link_status, hosts)
144
145
146def make_nodeplanner_json(debug=False):
147 # Input data
148 poel, link_type, link_data, link_status, hosts = get_graph_data(debug)
149
150 # Export data
151 points = []
152 for nodename, datadump in hosts.iteritems():
153 points.append({'name': datadump['nodename'], 'lat' : float(datadump['latitude']), 'lon' : float(datadump['longitude']), 'state' : datadump['status']})
154 links = []
155 for addr,leden in poel.iteritems():
156 for index,lid in enumerate(leden[:-1]):
157 for buur in leden[index + 1:]:
158 links.append({'master' : hosts[buur]['nodename'], 'slave': hosts[lid]['nodename'], 'state' : link_status[addr][4:].lower()})
159
160 # Format data
161 return json.dumps({'points' : points, 'links' : links})
162
163
164
165def make_graph(debug=False):
166 poel, link_type, link_data, link_status, hosts = get_graph_data(debug)
167 output = ''
168 if debug: print "# Building KML file"
169 output += HEADER
170 for nodename, datadump in hosts.iteritems():
171 output += POINT % datadump
172
173 for addr,leden in poel.iteritems():
174 if link_type[addr] == '11a':
175 color = 'green'
176 weight = 4
177 elif link_type[addr] == 'eth':
178 color = 'blue'
179 weight = 8
180 else:
181 color = 'black'
182 weight = 1
183 width = max(1,link_data[addr])
184 leden = sorted(set(leden))
185 for index,lid in enumerate(leden[:-1]):
186 for buur in leden[index + 1:]:
187 keys = {}
188 keys['styleId'] = link_status[addr]
189 for key, value in hosts[buur].iteritems():
190 keys[key + 'A'] = value
191 for key, value in hosts[lid].iteritems():
192 keys[key + 'B'] = value
193 output += LINE % keys
194 output += FOOTER
195 return output
196
197if __name__ == "__main__":
198 OUTFILE = os.path.join(os.getcwd(),'network.kml')
199 kml_data = make_graph(debug=True)
200 f = open(OUTFILE,'w')
201 f.write(kml_data)
202 f.close()
203 print "# COMPLETED find your output in %s\n" % OUTFILE
204
Note: See TracBrowser for help on using the repository browser.