source: genesis/tools/make-network-graph.py@ 13867

Last change on this file since 13867 was 12486, checked in by rick, 11 years ago

Allow link specific features

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 4.5 KB
Line 
1#!/usr/bin/env python
2# vim:ts=2:et:sw=2:ai
3#
4#
5# Build topological network graph
6#
7# Rick van der Zwet <info@rickvanderzwet.nl>
8#
9import gformat
10import glob
11import os
12import re
13import subprocess
14import sys
15import tempfile
16import yaml
17
18OUTFILE = os.path.join(os.getcwd(),'network.png')
19LINK_SPECIFIC = False
20
21try:
22 store = yaml.load(open('store.yaml','r'))
23except IOError:
24 store = {'uptime' : {}, 'snmp' : {}, 'traffic' : {}}
25 pass
26
27def pass_filter(host):
28 for t in sys.argv:
29 if t in host:
30 return True
31 return False
32
33nodes = {}
34
35def make_graph():
36 poel = {}
37 link_type = {}
38 link_data = {}
39 try:
40 for host in gformat.get_hostlist():
41 # Filter should be proper argument
42 if not pass_filter(host):
43 continue
44 print "## Processing host", host
45 datadump = gformat.get_yaml(host)
46 nodename = datadump['nodename']
47 iface_keys = [elem for elem in datadump.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
48 nodes[nodename] = datadump
49 for iface_key in iface_keys:
50 l = datadump[iface_key]['ip']
51 addr, mask = l.split('/')
52
53 # Not parsing of these folks please
54 if not gformat.valid_addr(addr):
55 continue
56
57 addr = gformat.parseaddr(addr)
58 mask = int(mask)
59 addr = addr & ~((1 << (32 - mask)) - 1)
60 nk = nodename + ':' + datadump[iface_key]['autogen_ifname']
61 if poel.has_key(addr):
62 poel[addr] += [nk]
63 else:
64 poel[addr] = [nk]
65 # Assume all ns_ip to be 11a for a moment
66 if datadump[iface_key].has_key('ns_ip'):
67 link_type[addr] = '11a'
68 else:
69 link_type[addr] = datadump[iface_key]['type']
70
71 link_data[addr] = 1
72 iface = datadump[iface_key]['autogen_ifname']
73 INTERVAL = 60 * 10
74 if store['uptime'].has_key(nodename) and store['snmp'].has_key(nodename) and store['traffic'].has_key(nodename):
75 if store['traffic'][nodename].has_key(iface):
76 (b_in, b_out) = store['traffic'][nodename][iface]
77 uptime = store['uptime'][nodename]
78 t_kb = float(b_in + b_out) / 1024
79 print "# INFO: Found %s kB in %s seconds" % (t_kb, INTERVAL)
80 retval = ((t_kb) / uptime) * INTERVAL
81 link_data[addr] = retval
82
83 print "### ... %s %s [%s] is of type %s" % (iface, gformat.showaddr(addr), iface_key, link_type[addr])
84 except (KeyError, ValueError), e:
85 print "[FOUT] in '%s' interface '%s'" % (host,iface_key)
86 print e
87 sys.exit(1)
88
89 f = open('/tmp/test.dot','w')
90 sys.stderr.write("# Building temponary graph file\n")
91 print >> f, "digraph WirelessLeidenNetwork {"
92 print >> f ,"""
93graph [ fontsize = 10,
94 overlap = scalexy,
95 splines = true,
96 rankdir = LR,
97 ]
98node [ fontsize = 10, ]
99edge [ fontsize = 10, ]
100"""
101 for node in sorted(nodes.keys()):
102 datadump = nodes[node]
103 print "# Processing node:", node
104 lines = [node]
105 for ik in datadump['autogen_iface_keys']:
106 print "# .. ", ik
107 if 'alias' in ik or 'wlan' in datadump[ik]['autogen_ifname']:
108 continue
109 if datadump[ik].has_key('ns_mac'):
110 lines.append('<%(autogen_ifname)s> %(bridge_type)s at %(autogen_ifname)s - %(ns_mac)s\\n%(ssid)s\\n%(ns_ip)s' % datadump[ik])
111 else:
112 lines.append('<%(autogen_ifname)s> %(autogen_ifname)s' % datadump[ik])
113 print >> f,"""
114"%s" [
115shape = "record"
116label = "%s"
117];
118""" % (node, "|".join(lines))
119
120
121 for addr,leden in poel.iteritems():
122 if link_type[addr] == '11a':
123 color = 'green'
124 weight = 4
125 elif link_type[addr] == 'eth':
126 color = 'blue'
127 weight = 8
128 else:
129 color = 'black'
130 weight = 1
131 width = max(1,link_data[addr])
132 leden = sorted(set(leden))
133 for index,lid in enumerate(leden[:-1]):
134 for buur in leden[index + 1:]:
135 if LINK_SPECIFIC:
136 print >> f,' %s -> %s [color="%s", weight="%s", style="setlinewidth(%s)"]' % (lid, buur, color, weight, width)
137 else:
138 print >> f,' %s -> %s [color="%s", weight="%s", style="setlinewidth(%s)"]' % (lid.split(':')[0], buur.split(':')[0], color, weight, width)
139 print >> f, "}"
140 f.flush()
141 sys.stderr.write("# Plotting temponary graph file using graphviz\n")
142 retval = subprocess.call(["neato","-Tpng",f.name, "-o", OUTFILE])
143 if retval != 0:
144 sys.stderr.write("# FAILED [%i]\n" % retval)
145 subprocess.call(["cat",f.name])
146 exit(1)
147 sys.stderr.write("# COMPLETED find your output in %s\n" % OUTFILE)
148
149
150if __name__ == "__main__":
151 make_graph()
152
Note: See TracBrowser for help on using the repository browser.