Compare commits

..

No commits in common. "62f059b4613030d0104764ce3eb9ea6a47a38e79" and "2b44a5bbad358d482e64ae8e16c83e09ff056d8b" have entirely different histories.

4 changed files with 85 additions and 70 deletions

46
app.py
View File

@ -1,15 +1,12 @@
#!/usr/bin/env python #!/usr/bin/env python
import random
import uuid
import logging
import sentry_sdk import sentry_sdk
import communicator
import consumerlocator
import messagesender
import time import time
from communicator import Communicator
from consumerlocator import ConsumerLocator
from messagesender import MessageSender
""" """
Main entrypoint Main Flask RESTful API
""" """
__author__ = "@tormakris" __author__ = "@tormakris"
@ -18,18 +15,29 @@ __module_name__ = "app"
__version__text__ = "1" __version__text__ = "1"
sentry_sdk.init("https://3fa5ae886ba1489092ad49a93cb419c1@sentry.kmlabz.com/9") sentry_sdk.init("https://3fa5ae886ba1489092ad49a93cb419c1@sentry.kmlabz.com/9")
logging.basicConfig(level=logging.INFO)
LOGGER = logging.getLogger(__name__)
if __name__ == "__main__": if __name__ == "__main__":
LOGGER.info("Producer started") print("Producer: init")
generateduuid = str(uuid) comm = communicator.Communicator()
LOGGER.debug(f"My uuid is {generateduuid}") conslist = consumerlocator.ConsumerLocator()
consumerlocator = ConsumerLocator() conslist.initcommunicator(comm)
communicator = Communicator(consumerlocator=consumerlocator,uuid=uuid) message = messagesender.MessageSender()
messagesender = MessageSender(communicator=communicator)
while True: conslist.learnconsumerlist()
LOGGER.info("Sending message to consumer") print("Producer: started sending")
messagesender.sendmessage() for i in range(30):
time.sleep(random.random()) msg = message.createMessage(20)
print("Producer: trying to send ", i, "th message: ", msg)
available = False
if conslist.updateconsumer() is None:
print("Producer: no consumer available (waiting a bit)")
time.sleep(1)
else:
available = True
if available:
comm.sendmessage(msg)
print("Producer: message sent")
else:
print("Producer: failed to send message")
print("Producer: finished")

View File

@ -1,8 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
import logging
import random import random
import requests import requests
from consumerlocator import ConsumerLocator from singleton import Singleton
""" """
Communicator module Communicator module
@ -13,54 +13,32 @@ __copyright__ = "Copyright 2020, GoldenPogácsa Team"
__module_name__ = "messagesender" __module_name__ = "messagesender"
__version__text__ = "1" __version__text__ = "1"
logging.basicConfig(level=logging.INFO) class Communicator(Singleton):
LOGGER = logging.getLogger(__name__)
class Communicator:
""" """
Class handling low level communication with consumers. Class handling low level communication with consumers.
""" """
def __init__(self, consumerlocator: ConsumerLocator, uuid):
"""
Initialize object
:param consumerlocator:
:param uuid:
"""
self.consumerlocator=consumerlocator
self.uuid = uuid
def sendmessage(self, message: str) -> None: def sendmessage(self, message: str) -> None:
""" """
Send message to consumer. Send message to consumer.
:param message: :param message:
:return: none :return: none
""" """
currentconsumer=self.consumerlocator.getcurrentconsumer() return None
LOGGER.debug(f"Sending message to {currentconsumer}")
requests.post(f'http://{currentconsumer}/log', json={'uuid': self.uuid, 'message': message})
def discoveravailableconsumers(self) -> list: def discoveravailableconsumers(self) -> list:
""" """
Get the list of available consumer from the current primary consumer. Get the list of available consumer from the current primary consumer.
:return: :return:
""" """
currentconsumer = self.consumerlocator.getcurrentconsumer() return ["10.69.42.1","10.42.69.1","10.10.10.10","10.6.66.1"]
response = requests.get(f'http://{currentconsumer}/consumer')
json = response.json()
LOGGER.debug(f"List of currently available consumers: {json}")
return json
def isconsumeravailable(self) -> bool: def isconsumeravailable(self) -> bool:
""" """
Readiness probe primary consumer. Readiness probe primary consumer.
:return: :return:
""" """
currentconsumer = self.consumerlocator.getcurrentconsumer() return bool(random.getrandbits(1))
response = requests.get(f'http://{currentconsumer}/consumer')
isavailable = response.status_code == 200
LOGGER.debug(f"Current consumer availability: {isavailable}")
return isavailable
def checkconsumer(self, consumer: str) -> bool: def checkconsumer(self, consumer: str) -> bool:
""" """
@ -68,7 +46,4 @@ class Communicator:
:param consumer: :param consumer:
:return: :return:
""" """
response = requests.get(f'http://{consumer}/consumer') return bool(random.getrandbits(1))
isavailable = response.status_code == 200
LOGGER.debug(f"Consumer {consumer} availability: {isavailable}")
return isavailable

View File

@ -1,46 +1,48 @@
#!/usr/bin/env python #!/usr/bin/env python
import logging
import random import random
import string import string
from communicator import Communicator
""" """
Message sender component Main Flask RESTful API
""" """
__author__ = "@kovacsbence" __author__ = "@tormakris"
__copyright__ = "Copyright 2020, GoldenPogácsa Team" __copyright__ = "Copyright 2020, GoldenPogácsa Team"
__module_name__ = "messagesender" __module_name__ = "messagesender"
__version__text__ = "1" __version__text__ = "1"
logging.basicConfig(level=logging.INFO)
LOGGER = logging.getLogger(__name__)
class MessageSender: class MessageSender:
""" """
Üzenetek küldéséért felelős komponens. Üzenetek küldéséért felelős komponens.
""" """
def __init__(self, communicator: Communicator): def __init__(self):
""" """
Inicializálja az osztályt. Inicializálja az osztályt.
""" """
self.communicator = communicator pass
def randomstring(self, stringLength) -> str:
def randomString(self, stringLength):
"""Generate a random string of fixed length """ """Generate a random string of fixed length """
letters = string.ascii_lowercase letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength)) return ''.join(random.choice(letters) for i in range(stringLength))
def sendmessage(self, message: str = "") -> None:
def createMessage(self, p) -> str:
""" """
Uzenet letrehozasa Ez egy metodus
:param message: :param szam:
:param szoveg:
:return: str tipus :return: str tipus
""" """
if not message: data = self.randomString(p)
data = self.randomstring(32)
else: return str(data)
data = message pass
self.communicator.sendmessage(data)
if __name__ == "__main__":
temp = MessageSender()
print(temp.createMessage(20))

30
singleton.py Normal file
View File

@ -0,0 +1,30 @@
#!/usr/bin/env python
"""
Singleton meta module
"""
__author__ = "@tormakris"
__copyright__ = "Copyright 2020, GoldenPogácsa Team"
__module_name__ = "singleton"
__version__text__ = "1"
class Singleton(object):
"""
Singleton metaclass
"""
_instances = {}
def __new__(class_, *args, **kwargs):
"""
New
:param args:
:param kwargs:
:return:
"""
if class_ not in class_._instances:
class_._instances[class_] = super(
Singleton, class_).__new__(
class_, *args, **kwargs)
return class_._instances[class_]