Commit 6dc66be1 authored by Ulysse Beaugnon's avatar Ulysse Beaugnon

Log is now on a new module so it can be included anywhere

parent 093e464e
import time
def log(message, verbose_level):
if verbose >= verbose_level:
print time.strftime("%d-%m-%Y %H:%M:%S : " + message)
import socket import socket
import uuid import uuid
import log
# create an upd socket # create an upd socket
# listen on it for incoming messages and forward them # listen on it for incoming messages and forward them
...@@ -20,7 +21,7 @@ class Ring: ...@@ -20,7 +21,7 @@ class Ring:
def __init__(self, entryPoint): def __init__(self, entryPoint):
# initialize the connection # initialize the connection
self.sock = socket.socket( socket.AF_INET666666, socket.SOCK_DGRAM ) self.sock = socket.socket( socket.AF_INET6, socket.SOCK_DGRAM )
self.sock.bind(('', 0)) self.sock.bind(('', 0))
self.me = RingMember(uuid.uuid1().int ,'', self.sock.getsockname()[1]) # TODO : get the address self.me = RingMember(uuid.uuid1().int ,'', self.sock.getsockname()[1]) # TODO : get the address
# to enter the ring # to enter the ring
...@@ -29,16 +30,17 @@ class Ring: ...@@ -29,16 +30,17 @@ class Ring:
self.successor = self.me self.successor = self.me
else: else:
self.send('FIND_SUCCESSOR ' + str(self.me.id) + ' ' + self.me.toString(), entrypoint) self.send('FIND_SUCCESSOR ' + str(self.me.id) + ' ' + self.me.toString(), entrypoint)
log.log('Init the ring with me = ' + self.me.toString(), 3)
# TODO : # TODO :
def handleMessages(self): def handleMessages(self):
# TODO : switch to log # TODO : switch to log
print 'Handling messages ...' log.log('Handling messages ...', 3)
pass pass
def send(self, message, target): def send(self, message, target):
# TODO : switch to log # TODO : switch to log
print 'Sending : ' + message + ' to ' + target.toString() log.log('Sending : ' + message + ' to ' + target.toString(), 5)
self.sock.sendTo(message, (target.ip, target.port)) self.sock.sendTo(message, (target.ip, target.port))
def findSuccessor(self, id, sender): def findSuccessor(self, id, sender):
......
...@@ -5,24 +5,21 @@ import upnpigd ...@@ -5,24 +5,21 @@ import upnpigd
import openvpn import openvpn
import random import random
import propagation import propagation
import log
VIFIB_NET = "2001:db8:42::/48" VIFIB_NET = "2001:db8:42::/48"
connection_dict = {} # to remember current connections we made connection_dict = {} # to remember current connections we made
free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5', free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5',
'client6', 'client7', 'client8', 'client9', 'client10')) 'client6', 'client7', 'client8', 'client9', 'client10'))
def log_message(message, verbose_level):
if config.verbose >= verbose_level:
print time.strftime("%d-%m-%Y %H:%M:%S : " + message)
# TODO : How do we get our vifib ip ? # TODO : How do we get our vifib ip ?
# TODO : flag in some way the peers that are connected to us so we don't connect to them # TODO : flag in some way the peers that are connected to us so we don't connect to them
# Or maybe we just don't care, # Or maybe we just don't care,
class PeersDB: class PeersDB:
def __init__(self, dbPath): def __init__(self, dbPath):
log_message('Connectiong to peers database', 4) log.log('Connectiong to peers database', 4)
self.db = sqlite3.connect(dbPath, isolation_level=None) self.db = sqlite3.connect(dbPath, isolation_level=None)
log_message('Initializing peers database', 4) log.log('Initializing peers database', 4)
self.db.execute("""CREATE TABLE IF NOT EXISTS peers self.db.execute("""CREATE TABLE IF NOT EXISTS peers
( id INTEGER PRIMARY KEY AUTOINCREMENT, ( id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT NOT NULL, ip TEXT NOT NULL,
...@@ -37,11 +34,11 @@ class PeersDB: ...@@ -37,11 +34,11 @@ class PeersDB:
"ORDER BY RANDOM() LIMIT ?", (nPeers,)) "ORDER BY RANDOM() LIMIT ?", (nPeers,))
def usePeer(self, id): def usePeer(self, id):
log_message('Updating peers database : using peer ' + str(id), 5) log.log('Updating peers database : using peer ' + str(id), 5)
self.db.execute("UPDATE peers SET used = 1 WHERE id = ?", (id,)) self.db.execute("UPDATE peers SET used = 1 WHERE id = ?", (id,))
def unusePeer(self, id): def unusePeer(self, id):
log_message('Updating peers database : unusing peer ' + str(id), 5) log.log('Updating peers database : unusing peer ' + str(id), 5)
self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,)) self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,))
...@@ -103,37 +100,37 @@ def getConfig(): ...@@ -103,37 +100,37 @@ def getConfig():
def startNewConnection(n): def startNewConnection(n):
try: try:
for id, ip, port, proto in peers_db.getUnusedPeers(n): for id, ip, port, proto in peers_db.getUnusedPeers(n):
log_message('Establishing a connection with id %s (%s:%s)' % (id,ip,port), 2) log.log('Establishing a connection with id %s (%s:%s)' % (id,ip,port), 2)
iface = free_interface_set.pop() iface = free_interface_set.pop()
connection_dict[id] = ( openvpn.client( ip, '--dev', iface, '--proto', proto, '--rport', str(port), connection_dict[id] = ( openvpn.client( ip, '--dev', iface, '--proto', proto, '--rport', str(port),
stdout=os.open('%s/vifibnet.client.%s.log' % (config.log_directory, id), os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ), stdout=os.open('%s/vifibnet.client.%s.log' % (config.log_directory, id), os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ),
iface) iface)
peers_db.usePeer(id) peers_db.usePeer(id)
except KeyError: except KeyError:
log_message("Can't establish connection with %s : no available interface" % ip, 2) log.log("Can't establish connection with %s : no available interface" % ip, 2)
pass pass
except Exception: except Exception:
traceback.print_exc() traceback.print_exc()
def killConnection(id): def killConnection(id):
try: try:
log_message('Killing the connection with id ' + str(id), 2) log.log('Killing the connection with id ' + str(id), 2)
p, iface = connection_dict.pop(id) p, iface = connection_dict.pop(id)
p.kill() p.kill()
free_interface_set.add(iface) free_interface_set.add(iface)
peers_db.unusePeer(id) peers_db.unusePeer(id)
except KeyError: except KeyError:
log_message("Can't kill connection to " + peer + ": no existing connection", 1) log.log("Can't kill connection to " + peer + ": no existing connection", 1)
pass pass
except Exception: except Exception:
log_message("Can't kill connection to " + peer + ": uncaught error", 1) log.log("Can't kill connection to " + peer + ": uncaught error", 1)
pass pass
def checkConnections(): def checkConnections():
for id in connection_dict.keys(): for id in connection_dict.keys():
p, iface = connection_dict[id] p, iface = connection_dict[id]
if p.poll() != None: if p.poll() != None:
log_message('Connection with %s has failed with return code %s' % (id, p.returncode), 3) log.log('Connection with %s has failed with return code %s' % (id, p.returncode), 3)
free_interface_set.add(iface) free_interface_set.add(iface)
peers_db.unusePeer(id) peers_db.unusePeer(id)
del connection_dict[id] del connection_dict[id]
...@@ -153,16 +150,17 @@ def refreshConnections(): ...@@ -153,16 +150,17 @@ def refreshConnections():
def handle_message(msg): def handle_message(msg):
script_type, common_name = msg.split() script_type, common_name = msg.split()
if script_type == 'client-connect': if script_type == 'client-connect':
log_message('Incomming connection from %s' % (common_name,), 3) log.log('Incomming connection from %s' % (common_name,), 3)
# TODO : check if we are not already connected to it # TODO : check if we are not already connected to it
elif script_type == 'client-disconnect': elif script_type == 'client-disconnect':
log_message('%s has disconnected' % (common_name,), 3) log.log('%s has disconnected' % (common_name,), 3)
else: else:
log_message('Unknow message recieved from the openvpn pipe : ' + msg, 1) log.log('Unknow message recieved from the openvpn pipe : ' + msg, 1)
def main(): def main():
# Get arguments # Get arguments
getConfig() getConfig()
log.verbose = config.verbose
(externalIp, externalPort) = upnpigd.GetExternalInfo(1194) (externalIp, externalPort) = upnpigd.GetExternalInfo(1194)
# Setup database # Setup database
...@@ -170,17 +168,17 @@ def main(): ...@@ -170,17 +168,17 @@ def main():
peers_db = PeersDB(config.db) peers_db = PeersDB(config.db)
# Launch babel on all interfaces # Launch babel on all interfaces
log_message('Starting babel', 3) log.log('Starting babel', 3)
babel = startBabel(stdout=os.open('%s/babeld.log' % (config.log_directory,), os.O_WRONLY | os.O_CREAT | os.O_TRUNC), babel = startBabel(stdout=os.open('%s/babeld.log' % (config.log_directory,), os.O_WRONLY | os.O_CREAT | os.O_TRUNC),
stderr=subprocess.STDOUT) stderr=subprocess.STDOUT)
# Create and open read_only pipe to get connect/disconnect events from openvpn # Create and open read_only pipe to get connect/disconnect events from openvpn
log_message('Creating pipe for openvpn events', 3) log.log('Creating pipe for openvpn events', 3)
r_pipe, write_pipe = os.pipe() r_pipe, write_pipe = os.pipe()
read_pipe = os.fdopen(r_pipe) read_pipe = os.fdopen(r_pipe)
# Establish connections # Establish connections
log_message('Starting openvpn server', 3) log.log('Starting openvpn server', 3)
serverProcess = openvpn.server(config.ip, write_pipe, '--dev', 'vifibnet', serverProcess = openvpn.server(config.ip, write_pipe, '--dev', 'vifibnet',
stdout=os.open('%s/vifibnet.server.log' % (config.log_directory,), os.O_WRONLY | os.O_CREAT | os.O_TRUNC)) stdout=os.open('%s/vifibnet.server.log' % (config.log_directory,), os.O_WRONLY | os.O_CREAT | os.O_TRUNC))
startNewConnection(config.client_count) startNewConnection(config.client_count)
...@@ -188,6 +186,9 @@ def main(): ...@@ -188,6 +186,9 @@ def main():
# Timed refresh initializing # Timed refresh initializing
next_refresh = time.time() + config.refresh_time next_refresh = time.time() + config.refresh_time
# initializing the ring to propagate the peers
ring = propagation.Ring(None)
# main loop # main loop
try: try:
while True: while True:
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment