The trafic is now taken into account to choose the tunnel to delete
[re6stnet.git] / tunnel.py
1 import os, random, traceback, time, struct, subprocess, operator, math
2 import plib, utils, db
3
4 log = None
5 smooth = 0.3 # this is used to smooth the traffic sampling. Lower value
6 # mean more smooth
7 protected = 0.2 # ratio of the tunnels protected against kill because they are
8 # used a lot
9
10
11 # Be carfull the refresh interval should let the routes be established
12
13
14 class Connection:
15
16 def __init__(self, address, write_pipe, hello, iface, prefix,
17 ovpn_args):
18 self.process = plib.client(address, write_pipe, hello, '--dev', iface,
19 *ovpn_args, stdout=os.open(os.path.join(log,
20 'vifibnet.client.%s.log' % (prefix,)),
21 os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
22 stderr=subprocess.STDOUT)
23
24 self.iface = iface
25 self.routes = 0
26 self._prefix = prefix
27 self.bandwidth = None
28 self._last_trafic = None
29
30 # TODO : update the stats
31 def refresh(self):
32 # Check that the connection is alive
33 if self.process.poll() != None:
34 utils.log('Connection with %s has failed with return code %s'
35 % (self._prefix, self.process.returncode), 3)
36 return False
37
38 self._updateBandwidth()
39 return True
40
41 def _updateBandwidth(self):
42 try:
43 f_rx = open('/sys/class/net/%s/statistics/rx_bytes' %
44 self.iface, 'r')
45 f_tx = open('/sys/class/net/%s/statistics/tx_bytes' %
46 self.iface, 'r')
47
48 trafic = int(f_rx.read()) + int(f_tx.read())
49 t = time.time()
50
51 if bool(self._last_trafic):
52 bw = (trafic - self._last_trafic) / (t -
53 self._last_trafic_update)
54 if bool(self.bandwidth):
55 self.bandwidth = ((1 - smooth) * self.bandwidth
56 + smooth * bw)
57 else:
58 self.bandwidth = bw
59
60 utils.log('New bandwidth calculated on iface %s : %s' %
61 (self.iface, self.bandwidth), 4)
62
63 self._last_trafic_update = t
64 self._last_trafic = trafic
65 except IOError: # This just means that the interface is downs
66 utils.log('Unable to calculate bandwidth on iface %s' %
67 self.iface, 4)
68
69
70 class TunnelManager:
71
72 def __init__(self, write_pipe, peer_db, openvpn_args, hello_interval,
73 refresh, connection_count, refresh_rate, iface_list, network):
74 self._write_pipe = write_pipe
75 self._peer_db = peer_db
76 self._connection_dict = {}
77 self._iface_to_prefix = {}
78 self._ovpn_args = openvpn_args
79 self._hello = hello_interval
80 self._refresh_time = refresh
81 self._network = network
82 self._net_len = len(network)
83 self._iface_list = iface_list
84 self.__indirect_connect = []
85 self.free_interface_set = set(('client1', 'client2', 'client3',
86 'client4', 'client5', 'client6',
87 'client7', 'client8', 'client9',
88 'client10', 'client11', 'client12'))
89 self.next_refresh = time.time()
90
91 self._client_count = int(math.ceil(float(connection_count) / 2.0))
92 self._refresh_count = int(math.ceil(refresh_rate * self._client_count))
93
94 def refresh(self):
95 utils.log('Refreshing the tunnels...', 2)
96 self._cleanDeads()
97 self._countRoutes()
98 self._removeSomeTunnels()
99 self._makeNewTunnels()
100 utils.log('Tunnels refreshed', 2)
101 self.next_refresh = time.time() + self._refresh_time
102
103 def _cleanDeads(self):
104 for prefix in self._connection_dict.keys():
105 if not self._connection_dict[prefix].refresh():
106 self._kill(prefix)
107 self._peer_db.flagPeer(prefix)
108
109 def _removeSomeTunnels(self):
110 # Get the candidates to killing
111 candidates = sorted(self._connection_dict, key=lambda p:
112 self._connection_dict[p].bandwidth)
113 candidates = sorted(candidates[0: int(math.ceil((1 - protected)
114 * len(candidates)))], key=lambda p:
115 self._connection_dict[p].routes)
116 for prefix in candidates[0: max(0, len(self._connection_dict) -
117 self._client_count + self._refresh_count)]:
118 self._kill(prefix)
119
120 def _kill(self, prefix):
121 utils.log('Killing the connection with %s...' % (prefix,), 2)
122 connection = self._connection_dict.pop(prefix)
123 try:
124 connection.process.kill()
125 except OSError:
126 # If the process is already exited
127 pass
128 self.free_interface_set.add(connection.iface)
129 self._peer_db.unusePeer(prefix)
130 del self._iface_to_prefix[connection.iface]
131 utils.log('Connection with %s killed' % (prefix,), 2)
132
133 def _makeNewTunnels(self):
134 i = 0
135 utils.log('Trying to make %i new tunnels...' %
136 (self._client_count - len(self._connection_dict)), 5)
137 try:
138 for prefix, address in self._peer_db.getUnusedPeers(
139 self._client_count - len(self._connection_dict)):
140 utils.log('Establishing a connection with %s' % prefix, 2)
141 iface = self.free_interface_set.pop()
142 self._connection_dict[prefix] = Connection(address,
143 self._write_pipe, self._hello, iface,
144 prefix, self._ovpn_args)
145 self._iface_to_prefix[iface] = prefix
146 self._peer_db.usePeer(prefix)
147 i += 1
148 utils.log('%u new tunnels established' % (i,), 3)
149 except KeyError:
150 utils.log("""Can't establish connection with %s
151 : no available interface""" % prefix, 2)
152 except Exception:
153 traceback.print_exc()
154
155 def _countRoutes(self):
156 utils.log('Starting to count the routes on each interface...', 3)
157 self._indirect_connect = []
158 for iface in self._iface_to_prefix.keys():
159 self._connection_dict[self._iface_to_prefix[iface]].routes = 0
160 f = open('/proc/net/ipv6_route', 'r')
161 for line in f:
162 ip, subnet_size, iface = struct.unpack('32s x 2s 106x %ss x'
163 % (len(line) - 142), line)
164 ip = bin(int(ip, 16))[2:].rjust(128, '0')
165
166 if ip.startswith(self._network):
167 iface = iface.strip()
168 subnet_size = int(subnet_size, 16)
169 utils.log('Route on iface %s detected to %s/%s'
170 % (iface, ip, subnet_size), 8)
171 if iface in self._iface_to_prefix.keys():
172 self._connection_dict[self._iface_to_prefix[iface]].routes += 1
173 if iface in self._iface_list and self._net_len < subnet_size < 128:
174 prefix = ip[self._net_len:subnet_size]
175 utils.log('A route to %s has been discovered on the LAN'
176 % (prefix,), 3)
177 self._peer_db.blacklist(prefix)
178
179 utils.log("Routes have been counted", 3)
180 for p in self._connection_dict.keys():
181 utils.log('Routes on iface %s : %s' % (
182 self._connection_dict[p].iface,
183 self._connection_dict[p].routes), 5)
184
185 def killAll(self):
186 for prefix in self._connection_dict.keys():
187 self._kill(prefix)