Typos in README
[re6stnet.git] / tunnel.py
1 import os, random, traceback, time
2 import plib, utils, db
3
4 log = None
5
6 class TunnelManager:
7
8 def __init__(self, write_pipe, peer_db, openvpn_args, refresh, connection_count, refresh_rate):
9 self._write_pipe = write_pipe
10 self._peer_db = peer_db
11 self._connection_dict = {}
12 self._ovpn_args = openvpn_args
13 self._refresh_time = refresh
14 self.free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5',
15 'client6', 'client7', 'client8', 'client9', 'client10'))
16 self.next_refresh = time.time()
17
18 # TODO : choose this automatically
19 self._client_count = connection_count/2
20 self._refresh_count = refresh_rate*self._client_count
21
22 def refresh(self):
23 utils.log('Refreshing the tunnels', 2)
24 self._cleanDeads()
25 self._removeSomeTunnels()
26 self._makeNewTunnels()
27 self.next_refresh = time.time() + self._refresh_time
28
29 def _cleanDeads(self):
30 for id in self._connection_dict.keys():
31 p, iface = self._connection_dict[id]
32 if p.poll() != None:
33 utils.log('Connection with %s has failed with return code %s' % (id, p.returncode), 3)
34 self.free_interface_set.add(iface)
35 self._peer_db.unusePeer(id)
36 del self._connection_dict[id]
37
38 def _removeSomeTunnels(self):
39 for i in range(0, max(0, len(self._connection_dict) - self._client_count + self._refresh_count)):
40 peer_id = random.choice(self._connection_dict.keys())
41 self._kill(peer_id)
42
43 def _kill(self, peer_id):
44 utils.log('Killing the connection with id ' + str(peer_id), 2)
45 p, iface = self._connection_dict.pop(peer_id)
46 p.kill()
47 self.free_interface_set.add(iface)
48 self._peer_db.unusePeer(peer_id)
49
50 def _makeNewTunnels(self):
51 #utils.log('Making %i new tunnels' % (self._client_count - len(self._connection_dict)), 3)
52 try:
53 for peer_id, ip, port, proto in self._peer_db.getUnusedPeers(self._client_count - len(self._connection_dict)):
54 utils.log('Establishing a connection with id %s (%s:%s)' % (peer_id, ip, port), 2)
55 iface = self.free_interface_set.pop()
56 self._connection_dict[peer_id] = ( plib.client( ip, self._write_pipe,
57 '--dev', iface, '--proto', proto, '--rport', str(port), *self._ovpn_args,
58 stdout=os.open(os.path.join(log, 'vifibnet.client.%s.log' % (peer_id,)),
59 os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ), iface)
60 self._peer_db.usePeer(peer_id)
61 except KeyError:
62 utils.log("Can't establish connection with %s : no available interface" % ip, 2)
63 except Exception:
64 traceback.print_exc()