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