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