meshenger/main.py

303 lines
9.2 KiB
Python
Raw Normal View History

2014-04-04 14:59:46 +02:00
#!/usr/bin/python
import socket, os, time, select, urllib, sys, threading, json, logging, logging.config
2014-11-07 16:30:33 +01:00
os.chdir(os.path.dirname(__file__)) # change present working directory to the one where this file is
logging.config.fileConfig('pylog.conf')
logger = logging.getLogger('meshenger'+'.main')
2014-04-04 13:40:46 +02:00
2014-04-04 14:59:46 +02:00
class Meshenger:
devices = {} #the dictionary of all the nodes this this node has seen. each ip-entry has a tuple of 'foreign index update time' and time when last seen
devices_old = {}
serve_port = "13338"
2014-04-04 14:59:46 +02:00
announce_port = 13337
2014-04-04 16:23:33 +02:00
#own_ip = "0.0.0.0"
msg_dir = os.path.relpath('msg/')
2014-04-04 18:39:17 +02:00
exitapp = False #to kill all threads on
index_last_update = str(int(time.time()))
node_expiry = 15 #the time to wait before removing a node form the discovered nodelist
2014-04-04 14:59:46 +02:00
2014-04-04 16:27:15 +02:00
def __init__(self):
2014-04-04 14:59:46 +02:00
os.system("echo 1 >> /proc/sys/net/ipv6/conf/br-lan/disable_ipv6")
os.system("echo 1 >> /proc/sys/net/ipv6/conf/br-hotspot/disable_ipv6")
2014-05-28 01:36:32 +02:00
self.own_ip = self.get_ip_adress().strip()
2014-11-07 16:21:10 +01:00
# this hash is needed in clientserve, so client can generate color
self.own_hash = self.hasj(self.own_ip)
2014-04-04 14:59:46 +02:00
2014-04-18 18:55:12 +02:00
if not os.path.exists(self.msg_dir):
os.mkdir(self.msg_dir)
logger.info('Making message directory')
2014-04-18 18:55:12 +02:00
self.init_index()
self.make_alias()
2014-04-04 18:39:17 +02:00
try:
d = threading.Thread(target=self.discover)
d.daemon = True
d.start()
a = threading.Thread(target=self.announce)
a.daemon = True
a.start()
2014-05-28 11:09:01 +02:00
n = threading.Thread(target=self.nodeserve)
2014-04-28 22:44:59 +02:00
n.daemon = True
n.start()
c = threading.Thread(target=self.clientserve)
c.daemon = True
c.start()
2014-04-21 11:57:16 +02:00
2014-04-04 18:39:17 +02:00
except (KeyboardInterrupt, SystemExit):
logger.info('exiting discovery thread')
2014-04-04 18:39:17 +02:00
d.join()
a.join()
2014-04-24 17:03:42 +02:00
b.join()
2014-04-28 22:44:59 +02:00
n.join()
c.join()
2014-04-04 18:39:17 +02:00
sys.exit()
except Exception as e:
2014-11-06 20:21:19 +01:00
logger.warning( 'Main __init__ thread exception: %s', repr(e) )
except:
logger.warning( 'Main __init__ unknown thread exception')
2014-04-04 18:39:17 +02:00
while True:
2014-11-06 15:41:35 +01:00
logger.debug('Entering main loop')
#
2014-04-04 16:27:15 +02:00
if len(self.devices) > 0:
logger.info('found %s device(s)', len(self.devices))
2014-04-04 14:59:46 +02:00
2014-05-27 22:56:11 +02:00
for device in self.devices.keys():
2014-11-05 17:42:51 +01:00
nodehash = self.hasj(device)
nodepath = os.path.join(os.path.abspath('nodes'), nodehash)
2014-11-05 17:42:51 +01:00
nodeupdatepath = os.path.join(nodepath, 'lastupdate')
2014-04-28 22:44:59 +02:00
logger.info('Checking age of foreign node index')
logger.info('%s Foreign announce timestamp', self.devices[device])
2014-05-16 01:32:59 +02:00
try:
foreign_node_update = open(nodeupdatepath).read()
except:
foreign_node_update = 0 #means it was never seen before
logger.info('%s Locally stored timestamp for device', foreign_node_update)
2014-04-24 14:31:48 +02:00
2014-04-24 16:37:30 +02:00
2014-04-24 16:23:50 +02:00
if self.devices[device] > foreign_node_update:
logger.info('Foreign node"s index is newer, proceed to download index')
self.get_index(device, nodepath)
logger.info('downloading messages')
2014-11-05 17:42:51 +01:00
self.get_messages(device, nodepath, nodehash)
self.build_index()
2014-05-28 11:09:01 +02:00
self.node_timestamp(device)
2014-04-28 22:44:59 +02:00
self.devices_old = dict(self.devices)
#check to see if a node has been missing for a while, if so remove it from self.devices
for device in self.devices_old.keys():
update_time = int(self.devices[device][1])
time_delta = int(time.time())- update_time
if time_delta >= self.node_expiry:
logger.info('Node '+device+' missing for '+str(self.node_expiry)+' seconds. Removing from list')
del self.devices[device]
2014-04-04 18:39:17 +02:00
time.sleep(5) #free process or ctrl+c
2014-04-28 22:44:59 +02:00
2014-04-24 16:23:50 +02:00
def node_timestamp(self, ip):
nodepath = os.path.abspath(os.path.join('nodes', self.hasj(ip)))
2014-05-16 01:32:59 +02:00
updatepath = os.path.join(nodepath, 'lastupdate')
with open(updatepath, 'wb') as lastupdate:
lastupdate.write(self.devices[ip][0])
2014-04-24 16:23:50 +02:00
#return updatepath
2014-04-04 13:40:46 +02:00
2014-04-04 16:27:15 +02:00
def announce(self):
2014-04-04 17:05:46 +02:00
"""
2014-04-24 16:23:50 +02:00
Announce the node's existance to other nodes
"""
logger.info('Announcing')
2014-04-04 18:39:17 +02:00
while not self.exitapp:
2015-05-21 16:02:37 +02:00
try:
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.sendto(self.index_last_update, ("ff02::1", self.announce_port))
#sock.close()
time.sleep(5)
except:
logger.warning('Failed to announce myself!')
2014-04-04 13:40:46 +02:00
2014-04-04 16:27:15 +02:00
def discover(self):
2014-04-04 17:05:46 +02:00
"""
2014-04-24 16:23:50 +02:00
Discover other devices by listening to the Meshenger announce port
"""
2014-04-04 13:40:46 +02:00
logger.info('Discovering')
2014-05-16 01:39:12 +02:00
bufferSize = 1024 # whatever you need?
2014-04-04 13:40:46 +02:00
2014-04-04 16:27:15 +02:00
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.bind(('::', self.announce_port))
s.setblocking(0)
2014-04-04 18:39:17 +02:00
while not self.exitapp:
2014-04-04 16:27:15 +02:00
result = select.select([s],[],[])[0][0].recvfrom(bufferSize)
ip = result[1][0]
#logger.debug('%s %s', ip, 'discovered')
2014-05-16 01:32:59 +02:00
node_path = os.path.join(os.path.abspath('nodes'), self.hasj(ip))
announce_time = str(int(time.time()))
if not os.path.exists(node_path) and ip != self.own_ip:
2014-04-24 16:37:30 +02:00
#loop for first time
self.ip_to_hash_path(ip) #make a folder /nodes/hash
self.devices[ip] = result[0], announce_time
#self.node_timestamp(ip) #make a local copy of the timestamp in /nodes/hash/updatetimestamp
logger.info('New node %s', ip)
2014-04-24 16:37:30 +02:00
elif os.path.exists(node_path) and ip != self.own_ip:
logger.info('Known node %s', ip)
self.devices[ip] = result[0], announce_time
2014-04-24 16:37:30 +02:00
2014-05-28 11:09:01 +02:00
2014-04-04 16:27:15 +02:00
time.sleep(1)
2014-04-04 13:40:46 +02:00
2014-04-28 22:44:59 +02:00
def nodeserve(self):
2014-04-21 11:57:16 +02:00
"""
2014-04-28 22:44:59 +02:00
Initialize the nodeserver
2014-04-24 16:23:50 +02:00
"""
logger.info('Serving to nodes')
2014-04-28 22:44:59 +02:00
import meshenger_nodeserve
meshenger_nodeserve.main()
def clientserve(self):
"""
Initialize the clientserver
"""
logger.info('Serving to client')
2014-04-28 22:44:59 +02:00
import meshenger_clientserve
2014-11-06 21:34:56 +01:00
# set a reference to this object
meshenger_clientserve.meshenger = self
2014-04-28 22:44:59 +02:00
meshenger_clientserve.main()
2014-11-06 21:34:56 +01:00
# meshenger_clientserve.build_index_callback = self.build_index
def init_index(self):
2014-11-06 21:52:50 +01:00
"""
Initialize the index. Read from disk or create new.
"""
logger.info('Checking own index for the first time\n')
if not os.path.exists('index'):
with open('index','wb') as index:
index.write('')
self.previous_index = []
else:
self.previous_index = open('index').readlines()
2014-11-06 21:34:56 +01:00
self.build_index()
2014-04-04 13:40:46 +02:00
2014-04-04 16:27:15 +02:00
def build_index(self):
2014-04-04 17:05:46 +02:00
"""
Make an index file of all the messages present on the node.
Save the time of the last update.
"""
2014-11-06 21:34:56 +01:00
logger.debug('build_index')
current_index = os.listdir(self.msg_dir)
if current_index != self.previous_index:
with open('index', 'wb') as index:
for message in os.listdir(self.msg_dir):
index.write(message)
index.write('\n')
self.index_last_update = str(int(time.time()))
2014-04-04 13:40:46 +02:00
logger.info('Index updated: %s', current_index)
2014-04-28 22:44:59 +02:00
with open('index_last_update', 'wb') as indexupdate:
indexupdate.write(self.index_last_update) ### misschien moet dit index_last_update zijn
self.previous_index = current_index
def make_alias(self):
"""
See if the node already has an alias (nickname) if not just use the IP-Hash
"""
if not os.path.exists('alias'):
with open('alias','wb') as alias:
self.alias = self.own_hash
alias.write(self.own_hash)
else:
self.alias = open('alias','rb').read().replace('\n','') #should we replace the newline?
pass
logger.debug('Alias is "'+self.alias+'"')
2014-04-04 13:40:46 +02:00
2014-04-04 16:27:15 +02:00
def get_index(self,ip, path):
2014-04-04 17:05:46 +02:00
"""
Download the indices from other nodes.
"""
2014-04-04 13:40:46 +02:00
os.system('wget http://['+ip+'%adhoc0]:'+self.serve_port+'/index -O '+os.path.join(path,'index'))
2014-04-04 13:40:46 +02:00
2014-11-05 17:42:51 +01:00
def get_messages(self, ip, path, hash):
2014-04-04 17:05:46 +02:00
"""
2014-04-24 16:23:50 +02:00
Get new messages from other node based on it's index file
"""
try:
with open(os.path.join(path,'index')) as index:
index = index.read().split('\n')
for message in index:
messagepath = os.path.join(os.path.abspath(self.msg_dir), message)
if not os.path.exists(messagepath):
logger.info('downloading %s to %s', message, messagepath)
os.system('wget http://['+ip+'%adhoc0]:'+self.serve_port+'/msg/'+message+' -O '+messagepath)
2014-11-05 17:42:51 +01:00
with open(messagepath, 'r+') as f:
data=json.load(f)
data['hops']=str(int(data['hops'])+1)
data['node']=hash
f.seek(0)
json.dump(data, f)
except:
logger.info('Failed to download messages')
pass
2014-04-04 13:40:46 +02:00
def ip_to_hash_path(self, ip):
2014-04-04 17:05:46 +02:00
"""
2014-04-24 16:23:50 +02:00
Convert a node's ip into a hash and make a directory to store it's files
"""
if not os.path.exists('nodes'):
os.mkdir('nodes')
nodepath = os.path.join(os.path.abspath('nodes'), self.hasj(ip))
2014-04-04 16:27:15 +02:00
if not os.path.exists(nodepath):
os.mkdir(nodepath)
2014-04-04 13:40:46 +02:00
2014-04-04 16:27:15 +02:00
return nodepath
2014-04-04 13:40:46 +02:00
2014-11-05 17:42:51 +01:00
def hasj(self, ip):
"""
Convert a node's ip into a hash
"""
import hashlib
hasj = hashlib.md5(ip).hexdigest()
return hasj
2014-04-04 13:40:46 +02:00
2014-04-04 16:27:15 +02:00
def get_ip_adress(self):
2014-04-04 17:05:46 +02:00
"""
2014-04-24 16:23:50 +02:00
Hack to adhoc0's inet6 adress
"""
2014-11-07 16:50:34 +01:00
#TODO possibly check if it's an empty file
2014-04-04 16:27:15 +02:00
if not os.path.isfile('interfaceip6adress'):
2014-05-28 11:09:01 +02:00
os.system('ifconfig -a adhoc0 | grep inet6 > /root/meshenger/interfaceip6adress')
with open('/root/meshenger/interfaceip6adress', 'r') as a:
2014-04-04 16:27:15 +02:00
return a.read().split()[2].split('/')[0]
2014-04-04 13:40:46 +02:00
2014-04-04 16:23:33 +02:00
2014-04-04 17:05:46 +02:00
if __name__ == "__main__":
logger.info("starting main...")
2014-04-04 18:39:17 +02:00
try:
meshenger = Meshenger()
except (KeyboardInterrupt, SystemExit):
exitapp = True
raise