source: genesis/tools/make_network_kml.py@ 14377

Last change on this file since 14377 was 14374, checked in by rick, 6 years ago

Update gformat to FreeBSD new default python3

  • Property svn:executable set to *
File size: 5.8 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 if not 'ip' in datadump[iface_key]:
90 continue
91
92 l = datadump[iface_key]['ip']
93 addr, mask = l.split('/')
94
95 # Not parsing of these folks please
96 if not gformat.valid_addr(addr):
97 continue
98
99 addr = gformat.parseaddr(addr)
100 mask = int(mask)
101 addr = addr & ~((1 << (32 - mask)) - 1)
102 if addr in poel:
103 poel[addr] += [nodename]
104 if link_status[addr] == 'linkUp':
105 if datadump['status'] == 'planned':
106 link_status[addr] = 'linkPlanned'
107 elif datadump[iface_key]['status'] == 'planned':
108 link_status[addr] = 'linkPlanned'
109 elif datadump[iface_key]['status'] == 'down':
110 link_status[addr] = 'linkDown'
111 else:
112 poel[addr] = [nodename]
113 # Assume all ns_ip to be 11a for a moment
114 if 'ns_ip' in datadump[iface_key]:
115 link_type[addr] = '11a'
116 else:
117 link_type[addr] = datadump[iface_key]['type']
118
119 if datadump['status'] == 'planned':
120 link_status[addr] = 'linkPlanned'
121 elif datadump[iface_key]['status'] == 'planned':
122 link_status[addr] = 'linkPlanned'
123 elif datadump[iface_key]['status'] == 'down':
124 link_status[addr] = 'linkDown'
125 else:
126 link_status[addr] = 'linkUp'
127
128 link_data[addr] = 1
129 iface = datadump[iface_key]['autogen_ifname']
130 nodename = datadump['nodename']
131 INTERVAL = 60 * 10
132 if store and nodename in store['uptime'] and nodename in store['snmp'] and nodename in store['traffic']:
133 if store and iface in store['traffic'][nodename]:
134 (b_in, b_out) = store['traffic'][nodename][iface]
135 uptime = store['uptime'][nodename]
136 t_kb = float(b_in + b_out) / 1024
137 if debug: print("# INFO: Found %s kB in %s seconds" % (t_kb, INTERVAL))
138 retval = ((t_kb) / uptime) * INTERVAL
139 link_data[addr] = retval
140
141 if debug: print("### %s [%s] is of type %s" % (gformat.showaddr(addr), iface_key, link_type[addr]))
142 except (KeyError, ValueError) as e:
143 if debug: print("[FOUT] in '%s' interface '%s'" % (host,iface_key))
144 if debug: print(e)
145 sys.exit(1)
146 return (poel, link_type, link_data, link_status, hosts)
147
148
149def make_nodeplanner_json(debug=False):
150 # Input data
151 poel, link_type, link_data, link_status, hosts = get_graph_data(debug)
152
153 # Export data
154 points = []
155 for nodename, datadump in hosts.iteritems():
156 points.append({'name': datadump['nodename'], 'lat' : float(datadump['latitude']), 'lon' : float(datadump['longitude']), 'state' : datadump['status']})
157 links = []
158 for addr,leden in poel.iteritems():
159 for index,lid in enumerate(leden[:-1]):
160 for buur in leden[index + 1:]:
161 links.append({'master' : hosts[buur]['nodename'], 'slave': hosts[lid]['nodename'], 'state' : link_status[addr][4:].lower()})
162
163 # Format data
164 return json.dumps({'points' : points, 'links' : links})
165
166
167
168def make_graph(debug=False):
169 poel, link_type, link_data, link_status, hosts = get_graph_data(debug)
170 output = ''
171 if debug: print("# Building KML file")
172 output += HEADER
173 for nodename, datadump in hosts.iteritems():
174 output += POINT % datadump
175
176 for addr,leden in poel.iteritems():
177 if link_type[addr] == '11a':
178 color = 'green'
179 weight = 4
180 elif link_type[addr] == 'eth':
181 color = 'blue'
182 weight = 8
183 else:
184 color = 'black'
185 weight = 1
186 width = max(1,link_data[addr])
187 leden = sorted(set(leden))
188 for index,lid in enumerate(leden[:-1]):
189 for buur in leden[index + 1:]:
190 keys = {}
191 keys['styleId'] = link_status[addr]
192 for key, value in hosts[buur].iteritems():
193 keys[key + 'A'] = value
194 for key, value in hosts[lid].iteritems():
195 keys[key + 'B'] = value
196 output += LINE % keys
197 output += FOOTER
198 return output
199
200if __name__ == "__main__":
201 OUTFILE = os.path.join(os.getcwd(),'network.kml')
202 kml_data = make_graph(debug=True)
203 f = open(OUTFILE,'w')
204 f.write(kml_data)
205 f.close()
206 print("# COMPLETED find your output in %s\n" % OUTFILE)
207
Note: See TracBrowser for help on using the repository browser.