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