#! /usr/bin/env python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Name: peerlistcache.py
# Purpose:
#
# Author: d0c 54v4g3, Jeremy Arendt
#
# Created: 2005/10/24
# RCS-ID: $Id: peerlistcache.py,v 1.2 2005/11/30 00:58:00 inigo Exp $
# Copyright: (c) 2005
# Licence: See LICENCES.TXT
#-----------------------------------------------------------------------------
from threading import Timer,Lock
from socket import gethostbyaddr,error
from traceback import print_exc
from time import time
from g3peerid import GetClientName,GetPeerName,GetRawPeerid
class PeerListCache:
def __init__(self, doneflag):
self.doneflag = doneflag
self.counter = 0
self.lock = Lock()
self.peerinfo_db = {} #[address, uploaded total, downloaded total, client, name, rawformattedpeerid, actualpeerid , last time updated]
def GetPeerInfo(self, ip, peerid):
peerinfo = None
if self.lock.acquire(False):
if self.peerinfo_db.has_key(ip):
self.peerinfo_db[ip][7] = time()
peerinfo = self.peerinfo_db[ip]
else:
self.peerinfo_db[ip] = [None, 0, 0, '', '', '', peerid, time()]
self.lock.release()
if peerinfo:
return peerinfo
else:
return [None, 0, 0, '', '', '', None, time()]
def Stop(self):
print 'stopping'
self.timer.cancel()
def Start(self):
self.timer = Timer(5, self.OnTimer)
self.timer.start()
def OnTimer(self):
if self.doneflag.isSet():
print "TIMER: peerinfo timer ending s0"
return False
self.counter += 1
ip_list = []
peerid_list = []
self.lock.acquire(True)
# every 15 mins, purge items from peerinfo db that have not been accessed for 60mins
if not (self.counter % 180):
for ip in self.peerinfo_db.items():
if (ip[1][7] + 3600) < time():
self.peerinfo_db.pop(ip)
# collect list of unresolved peer names/ids
for key, value in self.peerinfo_db.items():
if self.doneflag.isSet():
break
if value[0] == None:
ip_list.append(key)
if value[3] == '':
peerid_list.append(key)
self.lock.release()
for ip in peerid_list:
if self.doneflag.isSet():
break
peer_id = self.peerinfo_db[ip][6]
if peer_id != None:
name = GetPeerName(peer_id)
client = GetClientName(peer_id)
raw_id = GetRawPeerid(peer_id)
else:
name = ''
client = ''
raw_id = ''
self.lock.acquire(True)
self.peerinfo_db[ip][3] = client
self.peerinfo_db[ip][4] = name
self.peerinfo_db[ip][5] = raw_id
self.peerinfo_db[ip][7] = time()
self.lock.release()
for ip in ip_list:
if self.doneflag.isSet():
break
address = self.get_address(ip)
self.lock.acquire(True)
self.peerinfo_db[ip][0] = address
self.peerinfo_db[ip][7] = time()
self.lock.release()
if self.doneflag.isSet():
print "TIMER: peerinfo timer ending s1"
return False
self.Start()
def get_address(self, ip):
try:
return gethostbyaddr(ip)[0]
except error:
return ip
|