Added small doc in README
[re6stnet.git] / tunnel.py
1 import os, random, traceback, time, struct
2 import plib, utils, db
3
4 log = None
5 smooth = 0.3
6
7 class Connection:
8
9 def __init__(self, address, write_pipe, hello, iface, prefix,
10 ovpn_args):
11 self.process = plib.client(address, write_pipe, hello, '--dev', iface,
12 *ovpn_args, stdout=os.open(os.path.join(log,
13 'vifibnet.client.%s.log' % (prefix,)),
14 os.O_WRONLY|os.O_CREAT|os.O_TRUNC))
15
16 self.iface = iface
17 self._prefix = prefix
18 self._creation_date = time.time()
19 self._bandwidth = None
20 self._last_trafic = None
21
22 # TODO : update the stats
23 def refresh(self):
24 # Check that the connection is alive
25 if self.process.poll() != None:
26 utils.log('Connection with %s has failed with return code %s'
27 % (self._prefix, self.process.returncode), 3)
28 return False
29
30 self._updateBandwidth()
31 return True
32
33 def _updateBandwidth(self):
34 try:
35 f_rx = open('/sys/class/net/%s/statistics/rx_bytes' %
36 self.iface, 'r')
37 f_tx = open('/sys/class/net/%s/statistics/tx_bytes' %
38 self.iface, 'r')
39
40 trafic = int(f_rx.read()) + int(f_tx.read())
41 t = time.time()
42
43 if bool(self._last_trafic):
44 bw = (trafic - self._last_trafic)/(t -
45 self._last_trafic_update)
46 if bool(self._bandwidth):
47 self._bandwidth = (1-smooth)*self._bandwidth + smooth*bw
48 else:
49 self._bandwidth = bw
50
51 utils.log('New bandwidth calculated on iface %s : %s' %
52 (self.iface, self._bandwidth), 4)
53
54 self._last_trafic_update = t
55 self._last_trafic = trafic
56 except IOError: # This just means that the interface is downs
57 utils.log('Unable to calculate bandwidth on iface %s' %
58 self.iface, 4)
59
60 class TunnelManager:
61
62 def __init__(self, write_pipe, peer_db, openvpn_args, hello_interval,
63 refresh, connection_count, refresh_rate):
64 self._write_pipe = write_pipe
65 self._peer_db = peer_db
66 self._connection_dict = {}
67 self._route_count = {}
68 self._ovpn_args = openvpn_args
69 self._hello = hello_interval
70 self._refresh_time = refresh
71 self.free_interface_set = set(('client1', 'client2', 'client3',
72 'client4', 'client5', 'client6',
73 'client7', 'client8', 'client9',
74 'client10', 'client11', 'client12'))
75 self.next_refresh = time.time()
76
77 self._client_count = connection_count/2
78 self._refresh_count = refresh_rate*self._client_count
79
80 def refresh(self):
81 utils.log('Refreshing the tunnels', 2)
82 self._cleanDeads()
83 self._countRoutes()
84 self._removeSomeTunnels()
85 self._makeNewTunnels()
86 self.next_refresh = time.time() + self._refresh_time
87
88 def _cleanDeads(self):
89 for prefix in self._connection_dict.keys():
90 if not self._connection_dict[prefix].refresh():
91 self._kill(prefix)
92
93 def _removeSomeTunnels(self):
94 for i in range(0, max(0, len(self._connection_dict) -
95 self._client_count + self._refresh_count)):
96 prefix = random.choice(self._connection_dict.keys())
97 self._kill(prefix)
98
99 def _kill(self, prefix):
100 utils.log('Killing the connection with ' + prefix, 2)
101 connection = self._connection_dict.pop(prefix)
102 try:
103 connection.process.kill()
104 except OSError:
105 # If the process is already exited
106 pass
107 self.free_interface_set.add(connection.iface)
108 self._peer_db.unusePeer(prefix)
109 del self._route_count[connection.iface]
110
111 def _makeNewTunnels(self):
112 utils.log('Trying to make %i new tunnels' %
113 (self._client_count - len(self._connection_dict)), 5)
114 try:
115 for prefix, address in self._peer_db.getUnusedPeers(
116 self._client_count - len(self._connection_dict)):
117 utils.log('Establishing a connection with %s' % prefix, 2)
118 iface = self.free_interface_set.pop()
119 self._connection_dict[prefix] = Connection(address,
120 self._write_pipe, self._hello, iface,
121 prefix, self._ovpn_args)
122 self._route_count[iface] = 0
123 self._peer_db.usePeer(prefix)
124 except KeyError:
125 utils.log("""Can't establish connection with %s
126 : no available interface""" % prefix, 2)
127 except Exception:
128 traceback.print_exc()
129
130 def _countRoutes(self):
131 utils.log('Starting to count the routes on each interface', 3)
132 for iface in self._route_count.keys():
133 self._route_count[iface] = 0
134 f = open('/proc/net/ipv6_route', 'r')
135 for line in f:
136 ip, subnet_size, iface = struct.unpack("""32s x 2s x 32x x 2x x
137 32x x 8x x 8x x 8x x 8x x %ss x""" % (len(line)-142), line)
138 iface = iface.replace(' ', '')
139 if iface in self._route_count.keys():
140 self._route_count[iface] += 1
141 for iface in self._route_count.keys():
142 utils.log('Routes on iface %s : %s' % (iface,self._route_count[iface] ), 5)
143
144