Added some comments
[re6stnet.git] / tunnel.py
1 import os, random, traceback, time, struct, subprocess, operator, math
2 import plib, utils, db
3
4 log = None
5 smooth = 0.3 # this is used to smooth the traffic sampling. Lower value
6 # mean more smooth
7
8 # Be carfull the refresh interval should let the routes be established
9
10
11 class Connection:
12
13 def __init__(self, address, write_pipe, hello, iface, prefix,
14 ovpn_args):
15 self.process = plib.client(address, write_pipe, hello, '--dev', iface,
16 *ovpn_args, stdout=os.open(os.path.join(log,
17 'vifibnet.client.%s.log' % (prefix,)),
18 os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
19 stderr=subprocess.STDOUT)
20
21 self.iface = iface
22 self.routes = 0
23 self._prefix = prefix
24 self._bandwidth = None
25 self._last_trafic = None
26
27 # TODO : update the stats
28 def refresh(self):
29 # Check that the connection is alive
30 if self.process.poll() != None:
31 utils.log('Connection with %s has failed with return code %s'
32 % (self._prefix, self.process.returncode), 3)
33 return False
34
35 # self._updateBandwidth()
36 return True
37
38 # Unused for now. By killing tunnels with significantly lower trafic
39 # in comparison to other tunnels, we hope to connect to nodes with
40 # better bandwith, in order to improve connectivity with destinations
41 # we are really interested in.
42 def _updateBandwidth(self):
43 try:
44 f_rx = open('/sys/class/net/%s/statistics/rx_bytes' %
45 self.iface, 'r')
46 f_tx = open('/sys/class/net/%s/statistics/tx_bytes' %
47 self.iface, 'r')
48
49 trafic = int(f_rx.read()) + int(f_tx.read())
50 t = time.time()
51
52 if bool(self._last_trafic):
53 bw = (trafic - self._last_trafic) / (t -
54 self._last_trafic_update)
55 if bool(self._bandwidth):
56 self._bandwidth = ((1 - smooth) * self._bandwidth
57 + smooth * bw)
58 else:
59 self._bandwidth = bw
60
61 utils.log('New bandwidth calculated on iface %s : %s' %
62 (self.iface, self._bandwidth), 4)
63
64 self._last_trafic_update = t
65 self._last_trafic = trafic
66 except IOError: # This just means that the interface is downs
67 utils.log('Unable to calculate bandwidth on iface %s' %
68 self.iface, 4)
69
70
71 class TunnelManager:
72
73 def __init__(self, write_pipe, peer_db, openvpn_args, hello_interval,
74 refresh, connection_count, refresh_rate, iface_list, network):
75 self._write_pipe = write_pipe
76 self._peer_db = peer_db
77 self._connection_dict = {}
78 self._iface_to_prefix = {}
79 self._ovpn_args = openvpn_args
80 self._hello = hello_interval
81 self._refresh_time = refresh
82 self._network = network
83 self._net_len = len(network)
84 self._iface_list = iface_list
85 self.free_interface_set = set(('client1', 'client2', 'client3',
86 'client4', 'client5', 'client6',
87 'client7', 'client8', 'client9',
88 'client10', 'client11', 'client12'))
89 self.next_refresh = time.time()
90
91 self._client_count = int(math.ceil(float(connection_count) / 2.0))
92 self._refresh_count = int(math.ceil(refresh_rate * self._client_count))
93
94 def refresh(self):
95 utils.log('Refreshing the tunnels...', 2)
96 self._cleanDeads()
97 self._countRoutes()
98 self._removeSomeTunnels()
99 self._makeNewTunnels()
100 utils.log('Tunnels refreshed', 2)
101 self.next_refresh = time.time() + self._refresh_time
102
103 def _cleanDeads(self):
104 for prefix in self._connection_dict.keys():
105 if not self._connection_dict[prefix].refresh():
106 self._kill(prefix)
107 self._peer_db.flagPeer(prefix)
108
109 def _removeSomeTunnels(self):
110 # Get the candidates to killing
111 candidates = sorted(self._connection_dict, key=lambda p:
112 self._connection_dict[p].routes)
113 print max(0, len(self._connection_dict) - self._client_count + self._refresh_count) # DEBUG
114 print self._client_count
115 for prefix in candidates[0: max(0, len(self._connection_dict) -
116 self._client_count + self._refresh_count)]:
117 self._kill(prefix)
118
119 def _kill(self, prefix):
120 utils.log('Killing the connection with %s...' % (prefix,), 2)
121 connection = self._connection_dict.pop(prefix)
122 try:
123 connection.process.kill()
124 except OSError:
125 # If the process is already exited
126 pass
127 self.free_interface_set.add(connection.iface)
128 self._peer_db.unusePeer(prefix)
129 del self._iface_to_prefix[connection.iface]
130 utils.log('Connection with %s killed' % (prefix,), 2)
131
132 def _makeNewTunnels(self):
133 i = 0
134 utils.log('Trying to make %i new tunnels...' %
135 (self._client_count - len(self._connection_dict)), 5)
136 try:
137 for prefix, address in self._peer_db.getUnusedPeers(
138 self._client_count - len(self._connection_dict)):
139 utils.log('Establishing a connection with %s' % prefix, 2)
140 iface = self.free_interface_set.pop()
141 self._connection_dict[prefix] = Connection(address,
142 self._write_pipe, self._hello, iface,
143 prefix, self._ovpn_args)
144 self._iface_to_prefix[iface] = prefix
145 self._peer_db.usePeer(prefix)
146 i += 1
147 utils.log('%u new tunnels established' % (i,), 3)
148 except KeyError:
149 utils.log("""Can't establish connection with %s
150 : no available interface""" % prefix, 2)
151 except Exception:
152 traceback.print_exc()
153
154 def _countRoutes(self):
155 utils.log('Starting to count the routes on each interface...', 3)
156 self._peer_db.clear_blacklist(0)
157 for iface in self._iface_to_prefix.keys():
158 self._connection_dict[self._iface_to_prefix[iface]].routes = 0
159 for line in open('/proc/net/ipv6_route'):
160 line = line.split()
161 ip = bin(int(line[0], 16))[2:].rjust(128, '0')
162
163 if ip.startswith(self._network):
164 iface = line[-1]
165 subnet_size = int(line[1], 16)
166 utils.log('Route on iface %s detected to %s/%s'
167 % (iface, ip, subnet_size), 8)
168 if iface in self._iface_to_prefix.keys():
169 self._connection_dict[self._iface_to_prefix[iface]].routes += 1
170 if iface in self._iface_list and self._net_len < subnet_size < 128:
171 prefix = ip[self._net_len:subnet_size]
172 utils.log('A route to %s has been discovered on the LAN'
173 % (prefix,), 3)
174 self._peer_db.blacklist(prefix, 0)
175
176 utils.log("Routes have been counted", 3)
177 for p in self._connection_dict.keys():
178 utils.log('Routes on iface %s : %s' % (
179 self._connection_dict[p].iface,
180 self._connection_dict[p].routes), 5)
181