# Path: monotonic.py
# def monotonic_time():
#     """
#     Clock that cannot be set and represents monotonic time since some
#     unspecified starting point. The unit is a second.
#     """
#     t = timespec()
#     _clock_gettime(CLOCK_MONOTONIC, byref(t))
#     return t.tv_sec + t.tv_nsec / 1e9


from monotonic import monotonic_time
import logging
import eventlet
import redis
import struct
		isRemove = 1 == conn.hdel(info_hash,peerNumber)
		
		#if removing the peer causes the hash set to no longer
		#exist, then remove it from the set of observed torrents
		if isRemove and not conn.exists(info_hash):
			conn.srem(Peers.SEEN_TORRENTS, info_hash)
		
		return isRemove
		
	def getPeerNumber(self,peer):
		#Pack the peer
		packedPeer = struct.pack(PEER_STRUCT,peer.ip,peer.port)
		return packedPeer
		
	def __call__(self):
		self.log.info('Started')
		
		if self.peerExpirationPeriod == 0:
			self.log.info('Peer expiration period is zero, peers never expire')
			return
			
		while True:
			eventlet.sleep(self.peerExpirationPeriod)
			self.removeExpiredPeers()
		
	def removeExpiredPeers(self):
		conn = self._getRedisConn()
		for info_hash in conn.sunion(Peers.SEEN_TORRENTS):
			self.log.info('Checking for expiry of peers @ %s',info_hash.encode('hex'))
			

# Path: monotonic.py
# def monotonic_time():
#     """
#     Clock that cannot be set and represents monotonic time since some
#     unspecified starting point. The unit is a second.
#     """
#     t = timespec()
#     _clock_gettime(CLOCK_MONOTONIC, byref(t))
#     return t.tv_sec + t.tv_nsec / 1e9


# Path: peers.py
from monotonic import monotonic_time
import logging
import eventlet
import redis
import struct

		isRemove = 1 == conn.hdel(info_hash,peerNumber)
		
		#if removing the peer causes the hash set to no longer
		#exist, then remove it from the set of observed torrents
		if isRemove and not conn.exists(info_hash):
			conn.srem(Peers.SEEN_TORRENTS, info_hash)
		
		return isRemove
		
	def getPeerNumber(self,peer):
		#Pack the peer
		packedPeer = struct.pack(PEER_STRUCT,peer.ip,peer.port)
		return packedPeer
		
	def __call__(self):
		self.log.info('Started')
		
		if self.peerExpirationPeriod == 0:
			self.log.info('Peer expiration period is zero, peers never expire')
			return
			
		while True:
			eventlet.sleep(self.peerExpirationPeriod)
			self.removeExpiredPeers()
		
	def removeExpiredPeers(self):
		conn = self._getRedisConn()
		for info_hash in conn.sunion(Peers.SEEN_TORRENTS):
			self.log.info('Checking for expiry of peers @ %s',info_hash.encode('hex'))
			

			for peerNumber,lastSeenTime in conn.hgetall(info_hash + Peers.LAST_SEEN_SUFFIX).iteritems():