2015-08-20 17:27:15 +02:00
|
|
|
import datetime
|
2016-10-13 19:35:55 +02:00
|
|
|
from collections import defaultdict
|
|
|
|
from lbrynet.core import utils
|
2015-08-20 17:27:15 +02:00
|
|
|
|
2017-01-27 17:18:40 +01:00
|
|
|
# Do not create this object except through PeerManager
|
2018-07-22 00:34:59 +02:00
|
|
|
class Peer:
|
2015-08-20 17:27:15 +02:00
|
|
|
def __init__(self, host, port):
|
|
|
|
self.host = host
|
|
|
|
self.port = port
|
2017-01-27 17:18:40 +01:00
|
|
|
# If a peer is reported down, we wait till this time till reattempting connection
|
2015-08-20 17:27:15 +02:00
|
|
|
self.attempt_connection_at = None
|
2017-01-27 17:18:40 +01:00
|
|
|
# Number of times this Peer has been reported to be down, resets to 0 when it is up
|
2015-08-20 17:27:15 +02:00
|
|
|
self.down_count = 0
|
2018-10-18 13:40:37 +02:00
|
|
|
# Number of successful connections (with full protocol completion) to this peer
|
2017-01-27 17:18:40 +01:00
|
|
|
self.success_count = 0
|
2015-08-20 17:27:15 +02:00
|
|
|
self.score = 0
|
|
|
|
self.stats = defaultdict(float) # {string stat_type, float count}
|
|
|
|
|
|
|
|
def is_available(self):
|
2016-10-13 19:35:55 +02:00
|
|
|
if self.attempt_connection_at is None or utils.today() > self.attempt_connection_at:
|
2015-08-20 17:27:15 +02:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def report_up(self):
|
|
|
|
self.down_count = 0
|
|
|
|
self.attempt_connection_at = None
|
|
|
|
|
2017-01-27 17:18:40 +01:00
|
|
|
def report_success(self):
|
|
|
|
self.success_count += 1
|
|
|
|
|
2015-08-20 17:27:15 +02:00
|
|
|
def report_down(self):
|
|
|
|
self.down_count += 1
|
|
|
|
timeout_time = datetime.timedelta(seconds=60 * self.down_count)
|
2016-10-13 19:35:55 +02:00
|
|
|
self.attempt_connection_at = utils.today() + timeout_time
|
2015-08-20 17:27:15 +02:00
|
|
|
|
|
|
|
def update_score(self, score_change):
|
|
|
|
self.score += score_change
|
|
|
|
|
|
|
|
def update_stats(self, stat_type, count):
|
|
|
|
self.stats[stat_type] += count
|
|
|
|
|
|
|
|
def __str__(self):
|
2016-09-10 08:10:43 +02:00
|
|
|
return '{}:{}'.format(self.host, self.port)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return 'Peer({!r}, {!r})'.format(self.host, self.port)
|