--ping-exit option in openvpn has been restored so their is no more zombies connections
[re6stnet.git] / db.py
1 #!/usr/bin/env python
2 import sqlite3, xmlrpclib, time
3 import utils
4
5 class PeerManager:
6
7 def __init__(self, dbPath, server, port, refresh_time, external_ip):
8 utils.log('Connectiong to peers database', 4)
9 self._db = sqlite3.connect(dbPath, isolation_level=None)
10 self._server = server
11 self._server_port = port
12 self._refresh_time = refresh_time
13 self._external_ip = external_ip
14 utils.log('Preparing peers database', 4)
15 try:
16 self._db.execute("UPDATE peers SET used = 0")
17 except sqlite3.OperationalError, e:
18 if e.args[0] == 'no such table: peers':
19 raise RuntimeError
20 self.next_refresh = time.time()
21
22 def populate(self, n, internal_ip, port, proto):
23 if self._external_ip != None:
24 address = (internal_ip, self._external_ip, port, proto)
25 else:
26 address = 0
27 utils.log('Connecting to remote server', 3)
28 self._proxy = xmlrpclib.ServerProxy('http://%s:%u' % (self._server, self._server_port))
29 utils.log('Updating peers database : populating', 2)
30 new_peer_list = self._proxy.getPeerList(n, address)
31 utils.log('New peers recieved from %s' % self._server, 5)
32 self._db.executemany("INSERT OR IGNORE INTO peers (ip, port, proto, used) VALUES (?,?,?,0)", new_peer_list)
33 if self._external_ip != None:
34 self._db.execute("DELETE FROM peers WHERE ip = ?", (self._external_ip,))
35 self.next_refresh = time.time() + self._refresh_time
36 utils.log('New peers : %s' % ', '.join(map(str, new_peer_list)), 5)
37
38 def getUnusedPeers(self, nPeers):
39 return self._db.execute("SELECT id, ip, port, proto FROM peers WHERE used = 0 "
40 "ORDER BY RANDOM() LIMIT ?", (nPeers,))
41
42 def usePeer(self, id):
43 utils.log('Updating peers database : using peer ' + str(id), 5)
44 self._db.execute("UPDATE peers SET used = 1 WHERE id = ?", (id,))
45
46 def unusePeer(self, id):
47 utils.log('Updating peers database : unusing peer ' + str(id), 5)
48 self._db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,))
49
50 def handle_message(self, msg):
51 script_type, arg = msg.split()
52 if script_type == 'client-connect':
53 utils.log('Incomming connection from %s' % (arg,), 3)
54 elif script_type == 'client-disconnect':
55 utils.log('%s has disconnected' % (arg,), 3)
56 elif script_type == 'route-up':
57 utils.log('External Ip : ' + arg, 3)
58 self._external_ip = arg
59 else:
60 utils.log('Unknow message recieved from the openvpn pipe : ' + msg, 1)