对于发出ping的slave,那其至少可以工作到发出ping的时间+ 2倍的k。在检查时,只要slave的最近一次更新的时间小于这个检查时间节点,就说明这个slave挂了。所以,设置一个dict,记录每个slave的存活时间。
class HeartBeat:
def __init__(self):
# do intialization if necessary
self.timeunite = 0
self.serverlivesofar = collections.defaultdict(int)
"""
@param: slaves_ip_list: a list of slaves'ip addresses
@param: k: An integer
@return: nothing
"""
def initialize(self, slaves_ip_list, k):
# write your code here
self.timeunite = 2*k
for ip in slaves_ip_list:
self.serverlivesofar[ip] = self.timeunite
"""
@param: timestamp: current timestamp in seconds
@param: slave_ip: the ip address of the slave server
@return: nothing
"""
def ping(self, timestamp, slave_ip):
# write your code here
if slave_ip not in self.serverlivesofar:
return
self.serverlivesofar[slave_ip] = timestamp + self.timeunite
"""
@param: timestamp: current timestamp in seconds
@return: a list of slaves'ip addresses that died
"""
def getDiedSlaves(self, timestamp):
# write your code here
res = []
for ip, timelive in self.serverlivesofar.items():
if timelive <= timestamp:
res.append(ip)
return res