Fixing config
[re6stnet.git] / tunnelmanager.py
1 import os, random, traceback
2 import plib, utils, db
3
4
5
6 class TunnelManager:
7
8 def __init__(self, write_pipe, peers_db, client_count, refresh_count):
9 self.write_pipe = write_pipe
10 self.peers_db = peers_db
11 self.connection_dict = {}
12 self.client_count = client_count
13 self.refresh_count = refresh_count
14 self.free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5',
15 'client6', 'client7', 'client8', 'client9', 'client10'))
16
17 def refresh(self):
18 self.cleanDeads()
19 self.removeSomeTunnels()
20 self.makeNewTunnels()
21
22 def cleanDeads(self):
23 for id in self.connection_dict.keys():
24 p, iface = self.connection_dict[id]
25 if p.poll() != None:
26 utils.log('Connection with %s has failed with return code %s' % (id, p.returncode), 3)
27 self.free_interface_set.add(iface)
28 self.peers_db.unusePeer(id)
29 del self.connection_dict[id]
30
31 def removeSomeTunnels(self):
32 for i in range(0, max(0, len(self.connection_dict) - self.client_count + self.refresh_count)):
33 peer_id = random.choice(self.connection_dict.keys())
34 kill(peer_id)
35
36 def kill(self, peer_id):
37 utils.log('Killing the connection with id ' + str(peer_id), 2)
38 p, iface = self.connection_dict.pop(peer_id)
39 p.kill()
40 self.free_interface_set.add(iface)
41 self.peers_db.unusePeer(peer_id)
42
43 def makeNewTunnels(self):
44 try:
45 for peer_id, ip, port, proto in self.peers_db.getUnusedPeers(self.client_count - len(self.connection_dict), self.write_pipe):
46 utils.log('Establishing a connection with id %s (%s:%s)' % (peer_id, ip, port), 2)
47 iface = self.free_interface_set.pop()
48 self.connection_dict[peer_id] = ( plib.client( ip, write_pipe, '--dev', iface, '--proto', proto, '--rport', str(port),
49 stdout=os.open(os.path.join(utils.config.log, 'vifibnet.client.%s.log' % (peer_id,)),
50 os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ), iface)
51 self.peers_db.usePeer(peer_id)
52 except KeyError:
53 utils.log("Can't establish connection with %s : no available interface" % ip, 2)
54 except Exception:
55 traceback.print_exc()
56
57 def handle_message(msg):
58 script_type, arg = msg.split()
59 if script_type == 'client-connect':
60 utils.log('Incomming connection from %s' % (arg,), 3)
61 elif script_type == 'client-disconnect':
62 utils.log('%s has disconnected' % (arg,), 3)
63 elif script_type == 'route-up':
64 utils.log('External Ip : ' + arg, 3)
65 else:
66 utils.log('Unknow message recieved from the openvpn pipe : ' + msg, 1)