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