Put all annexes python files into a subfolder
[re6stnet.git] / re6st / tunnel.py
1 import os, traceback, time, subprocess, math, logging
2 import plib
3
4 smooth = 0.3 # this is used to smooth the traffic sampling. Lower value
5 # mean more smooth
6 protected = 0.2 # ratio of the tunnels protected against kill because they are
7 # used a lot
8
9 # Be carfull the refresh interval should let the routes be established
10
11
12 class Connection:
13
14 def __init__(self, address, write_pipe, hello, iface, prefix,
15 ovpn_args):
16 self.process = plib.client(address, write_pipe, hello, '--dev', iface,
17 *ovpn_args, stdout=os.open(os.path.join(log,
18 're6stnet.client.%s.log' % (prefix,)),
19 os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
20 stderr=subprocess.STDOUT)
21
22 self.iface = iface
23 self.routes = 0
24 self._prefix = prefix
25 self.bandwidth = None
26 self._last_trafic = None
27
28 def refresh(self):
29 # Check that the connection is alive
30 if self.process.poll() != None:
31 logging.info('Connection with %s has failed with return code %s'
32 % (self._prefix, self.process.returncode))
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 logging.debug('New bandwidth calculated on iface %s : %s' %
62 (self.iface, self.bandwidth))
63
64 self._last_trafic_update = t
65 self._last_trafic = trafic
66 except IOError: # This just means that the interface is down
67 logging.debug('Unable to calculate bandwidth on iface %s' %
68 self.iface)
69
70
71 class TunnelManager:
72
73 def __init__(self, write_pipe, peer_db, openvpn_args, hello_interval,
74 refresh, connection_count, refresh_count, 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
86 self.next_refresh = time.time()
87 self._next_tunnel_refresh = time.time()
88
89 self._client_count = (connection_count + 1) // 2
90 self._refresh_count = refresh_count
91 self.free_interface_set = set('client' + str(i)
92 for i in xrange(1, self._client_count + 1))
93
94 def refresh(self):
95 logging.info('Refreshing the tunnels...')
96 self._cleanDeads()
97 if self._next_tunnel_refresh < time.time():
98 self._countRoutes()
99 self._removeSomeTunnels()
100 self._next_tunnel_refresh = time.time() + self._refresh_time
101 self._makeNewTunnels()
102 logging.debug('Tunnels refreshed')
103 self.next_refresh = time.time() + 5
104
105 def _cleanDeads(self):
106 for prefix in self._connection_dict.keys():
107 if not self._connection_dict[prefix].refresh():
108 self._kill(prefix)
109 self._peer_db.flagPeer(prefix)
110
111 def _removeSomeTunnels(self):
112 # Get the candidates to killing
113 candidates = sorted(self._connection_dict, key=lambda p:
114 self._connection_dict[p].bandwidth)
115 candidates = sorted(candidates[0: int(math.ceil((1 - protected)
116 * len(candidates)))], key=lambda p:
117 self._connection_dict[p].routes)
118 for prefix in candidates[0: max(0, len(self._connection_dict) -
119 self._client_count + self._refresh_count)]:
120 self._kill(prefix)
121
122 def _kill(self, prefix):
123 logging.info('Killing the connection with %s/%u...'
124 % (hex(int(prefix, 2))[2:], len(prefix)))
125 connection = self._connection_dict.pop(prefix)
126 try:
127 connection.process.terminate()
128 except OSError:
129 # If the process is already exited
130 pass
131 self.free_interface_set.add(connection.iface)
132 self._peer_db.unusePeer(prefix)
133 del self._iface_to_prefix[connection.iface]
134 logging.trace('Connection with %s/%u killed'
135 % (hex(int(prefix, 2))[2:], len(prefix)))
136
137 def _makeNewTunnels(self):
138 i = 0
139 logging.trace('Trying to make %i new tunnels...' %
140 (self._client_count - len(self._connection_dict)))
141 try:
142 for prefix, address in self._peer_db.getUnusedPeers(
143 self._client_count - len(self._connection_dict)):
144 logging.info('Establishing a connection with %s/%u' %
145 (hex(int(prefix, 2))[2:], len(prefix)))
146 iface = self.free_interface_set.pop()
147 self._connection_dict[prefix] = Connection(address,
148 self._write_pipe, self._hello, iface,
149 prefix, self._ovpn_args)
150 self._iface_to_prefix[iface] = prefix
151 self._peer_db.usePeer(prefix)
152 i += 1
153 logging.trace('%u new tunnels established' % (i,))
154 except KeyError:
155 logging.warning("""Can't establish connection with %s
156 : no available interface""" % prefix)
157 except Exception:
158 traceback.print_exc()
159
160 def _countRoutes(self):
161 logging.debug('Starting to count the routes on each interface...')
162 self._peer_db.clear_blacklist(0)
163 for iface in self._iface_to_prefix.keys():
164 self._connection_dict[self._iface_to_prefix[iface]].routes = 0
165 for line in open('/proc/net/ipv6_route'):
166 line = line.split()
167 ip = bin(int(line[0], 16))[2:].rjust(128, '0')
168
169 if ip.startswith(self._network):
170 iface = line[-1]
171 subnet_size = int(line[1], 16)
172 logging.trace('Route on iface %s detected to %s/%s'
173 % (iface, ip, subnet_size))
174 if iface in self._iface_to_prefix.keys():
175 self._connection_dict[self._iface_to_prefix[iface]].routes += 1
176 if iface in self._iface_list and self._net_len < subnet_size < 128:
177 prefix = ip[self._net_len:subnet_size]
178 logging.debug('A route to %s (%s) has been discovered on the LAN'
179 % (hex(int(prefix), 2)[2:], prefix))
180 self._peer_db.blacklist(prefix, 0)
181
182 logging.debug("Routes have been counted")
183 for p in self._connection_dict.keys():
184 logging.trace('Routes on iface %s : %s' % (
185 self._connection_dict[p].iface,
186 self._connection_dict[p].routes))
187
188 def killAll(self):
189 for prefix in self._connection_dict.keys():
190 self._kill(prefix)