103 lines
3.1 KiB
Python
103 lines
3.1 KiB
Python
#!/usr/bin/env python
|
|
|
|
import datetime
|
|
import communicator
|
|
import os
|
|
|
|
"""
|
|
Consumer locator module, that manages the list of consumers.
|
|
"""
|
|
|
|
__author__ = "@dscharnitzky"
|
|
__copyright__ = "Copyright 2020, GoldenPogácsa Team"
|
|
__module_name__ = "consumerlocator"
|
|
__version__text__ = "1"
|
|
|
|
|
|
class ConsumerLocator:
|
|
|
|
"""
|
|
Manages the list of consumers.
|
|
"""
|
|
|
|
def __init__(self):
|
|
"""
|
|
Initialize class.
|
|
"""
|
|
os.environ["KnownConsumer"] = "MockRemoveMe"
|
|
self.consumerlist = [{"Host": os.environ["KnownConsumer"], "State": True, "LastOk": datetime.datetime.now()}]
|
|
self.currentconsumer = self.consumerlist[0]
|
|
print(self.currentconsumer)
|
|
|
|
def initcommunicator(self, comm: communicator.Communicator):
|
|
"""
|
|
Initialize the reference to the communicator
|
|
:param comm: is the communicator
|
|
"""
|
|
self.communicator = comm
|
|
|
|
def learnconsumerlist(self):
|
|
""""
|
|
Learns the list of consumers.
|
|
"""
|
|
recievedconsumerlist = self.communicator.discoveravailableconsumers()
|
|
if recievedconsumerlist is None:
|
|
return
|
|
for consumer in recievedconsumerlist:
|
|
self.consumerList.append({"Host": consumer, "State": True, "LastOk": datetime.datetime.now()})
|
|
self.updateconsumerlist()
|
|
|
|
def updateconsumerlist(self):
|
|
"""
|
|
Updates the consumer list based on their availability.
|
|
"""
|
|
removelist = []
|
|
for consumer in self.consumerlist:
|
|
if not self.communicator.checkconsumer(consumer["Host"]):
|
|
consumer["State"] = False
|
|
if datetime.datetime.now() - consumer["LastOk"] > datetime.timedelta(hours=1):
|
|
removelist.append(consumer)
|
|
else:
|
|
consumer["LastOk"] = datetime.datetime.now()
|
|
for rem in removelist:
|
|
self.consumerlist.remove(rem)
|
|
|
|
def updateconsumer(self):
|
|
"""
|
|
Checks all the consumers in the list and updates the current consumer if necessary.
|
|
:return: the current consumer or None if there are no available customers at the moment.
|
|
"""
|
|
self.updateconsumerlist()
|
|
|
|
if not self.checkcurrentconsumer():
|
|
|
|
newcurrentconsumer = None
|
|
|
|
for consumer in self.consumerlist:
|
|
if consumer["State"]:
|
|
newcurrentconsumer = consumer
|
|
break
|
|
|
|
self.currentconsumer = newcurrentconsumer
|
|
self.learnconsumerlist()
|
|
|
|
if self.currentconsumer is not None:
|
|
return self.currentconsumer["Host"]
|
|
else:
|
|
return None
|
|
|
|
def getcurrentconsumer(self):
|
|
"""
|
|
Returns the currently selected consumer.
|
|
:return: the current consumer
|
|
"""
|
|
return self.currentconsumer["Host"]
|
|
|
|
def checkcurrentconsumer(self):
|
|
"""
|
|
Check the consumers health.
|
|
:return: True if OK, False if fail
|
|
"""
|
|
# return self.communicator.checkconsumer(self.currentconsumer["Host"])
|
|
return True # TODO remove this line and uncomment the above
|