Prepare the peer db to separate the server advertisment and the getPeersLists
[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, server_port, refresh_time, external_ip, internal_ip, port, proto, db_size):
8 self._server_port = server_port
9 self._refresh_time = refresh_time
10 self._external_ip = external_ip
11 self._internal_ip = internal_ip
12 self._external_port = port
13 self._proto = proto
14 self._db_size = db_size
15
16 utils.log('Connectiong to peers database', 4)
17 self._db = sqlite3.connect(dbPath, isolation_level=None)
18 self._server = server
19 utils.log('Preparing peers database', 4)
20 try:
21 self._db.execute("UPDATE peers SET used = 0")
22 except sqlite3.OperationalError, e:
23 if e.args[0] == 'no such table: peers':
24 raise RuntimeError
25
26 self.next_refresh = time.time()
27
28 def refresh(self):
29 self._populate()
30 self.next_refresh = time.time() + self._refresh_time
31
32 def _populate(self):
33 if self._external_ip != None:
34 address = (self._internal_ip, self._external_ip, self._external_port, self._proto)
35 else:
36 address = 0
37 utils.log('Connecting to remote server', 3)
38 self._proxy = xmlrpclib.ServerProxy('http://%s:%u' % (self._server, self._server_port))
39 utils.log('Updating peers database : populating', 2)
40 new_peer_list = self._proxy.getPeerList(self._db_size, address)
41 utils.log('New peers recieved from %s' % self._server, 5)
42 self._db.executemany("INSERT OR IGNORE INTO peers (ip, port, proto, used) VALUES (?,?,?,0)", new_peer_list)
43 if self._external_ip != None:
44 self._db.execute("DELETE FROM peers WHERE ip = ?", (self._external_ip,))
45 utils.log('New peers : %s' % ', '.join(map(str, new_peer_list)), 5)
46
47 def getUnusedPeers(self, nPeers):
48 return self._db.execute("SELECT id, ip, port, proto FROM peers WHERE used = 0 "
49 "ORDER BY RANDOM() LIMIT ?", (nPeers,))
50
51 def usePeer(self, id):
52 utils.log('Updating peers database : using peer ' + str(id), 5)
53 self._db.execute("UPDATE peers SET used = 1 WHERE id = ?", (id,))
54
55 def unusePeer(self, id):
56 utils.log('Updating peers database : unusing peer ' + str(id), 5)
57 self._db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,))
58
59 def handle_message(self, msg):
60 script_type, arg = msg.split()
61 if script_type == 'client-connect':
62 utils.log('Incomming connection from %s' % (arg,), 3)
63 elif script_type == 'client-disconnect':
64 utils.log('%s has disconnected' % (arg,), 3)
65 elif script_type == 'route-up':
66 utils.log('External Ip : ' + arg, 3)
67 self._external_ip = arg
68 else:
69 utils.log('Unknow message recieved from the openvpn pipe : ' + msg, 1)