Remove shebangs from non-executable iles
[re6stnet.git] / db.py
1 import sqlite3, xmlrpclib, time
2 import utils
3
4 class PeerManager:
5
6 def __init__(self, dbPath, server, server_port, refresh_time, external_ip, internal_ip, port, proto, db_size):
7 self._refresh_time = refresh_time
8 self._external_ip = external_ip
9 self._internal_ip = internal_ip
10 self._external_port = port
11 self._proto = proto
12 self._db_size = db_size
13 self._proxy = xmlrpclib.ServerProxy('http://%s:%u' % (server, server_port))
14
15 utils.log('Connectiong to peers database', 4)
16 self._db = sqlite3.connect(dbPath, isolation_level=None)
17 utils.log('Preparing peers database', 4)
18 try:
19 self._db.execute("UPDATE peers SET used = 0")
20 except sqlite3.OperationalError, e:
21 if e.args[0] == 'no such table: peers':
22 raise RuntimeError
23
24 self.next_refresh = time.time()
25
26 def refresh(self):
27 utils.log('Refreshing the peers DB', 2)
28 self._declare()
29 self._populate()
30 self.next_refresh = time.time() + self._refresh_time
31
32 def _declare(self):
33 if self._external_ip != None:
34 utils.log('Declaring our connections info', 3)
35 self._proxy.declare((self._internal_ip, self._external_ip, self._external_port, self._proto))
36 else:
37 utils.log('Warning : could not declare the external ip because it is unknown', 4)
38
39 def _populate(self):
40 utils.log('Populating the peers DB', 2)
41 new_peer_list = self._proxy.getPeerList(self._db_size, self._internal_ip)
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 if arg != self._external_ip:
67 self._external_ip = arg
68 utils.log('External Ip : ' + arg, 3)
69 self._declare()
70 else:
71 utils.log('Unknow message recieved from the openvpn pipe : ' + msg, 1)