|
import time |
|
import logging |
|
from threading import Thread, Event, Timer |
|
from api import InstancesAPI |
|
|
|
class LoadBalancer: |
|
def __init__(self, polling_interval=10, max_retries=3, initial_delay=1): |
|
self.version = "0.0.1 V Beta" |
|
self.instances = [] |
|
self.polling_interval = polling_interval |
|
self.max_retries = max_retries |
|
self.initial_delay = initial_delay |
|
self.stop_event = Event() |
|
self.instances_api = InstancesAPI(self.instances) |
|
|
|
def register_instance(self, instance_url): |
|
if instance_url not in self.instances: |
|
self.instances.append(instance_url) |
|
logging.info(f"Registered instance {instance_url}") |
|
else: |
|
logging.info(f"Instance {instance_url} is already registered.") |
|
|
|
def remove_instance(self, instance_url): |
|
if instance_url in self.instances: |
|
self.instances.remove(instance_url) |
|
logging.info(f"Removed instance {instance_url}") |
|
else: |
|
logging.info(f"Instance {instance_url} not found for removal.") |
|
|
|
def get_reports(self): |
|
reports = self.instances_api.fetch_reports() |
|
for instance_url in self.instances[:]: |
|
if instance_url in reports: |
|
report = reports[instance_url] |
|
logging.info(f"Report from {instance_url}: {report}") |
|
self.process_report(instance_url, report) |
|
else: |
|
logging.error(f"Failed to get report from {instance_url}. Removing instance.") |
|
self.remove_instance(instance_url) |
|
|
|
def process_report(self, instance_url, report): |
|
|
|
logging.info(f"Processing report from {instance_url}") |
|
|
|
logging.info(f"Film Store: {report.get('film_store')}") |
|
logging.info(f"TV Store: {report.get('tv_store')}") |
|
logging.info(f"Cache Size: {report.get('cache_size')}") |
|
|
|
def start_polling(self): |
|
logging.info("Starting polling.") |
|
while not self.stop_event.is_set(): |
|
self.get_reports() |
|
time.sleep(self.polling_interval) |
|
logging.info("Polling stopped.") |
|
|
|
def stop_polling(self): |
|
logging.info("Stopping polling.") |
|
self.stop_event.set() |
|
|
|
if __name__ == "__main__": |
|
logging.basicConfig(level=logging.INFO) |
|
|
|
load_balancer = LoadBalancer() |
|
|
|
|
|
load_balancer.register_instance("http://localhost:5000") |
|
|
|
|
|
polling_thread = Thread(target=load_balancer.start_polling) |
|
polling_thread.start() |
|
|
|
|
|
Timer(300, load_balancer.stop_polling).start() |
|
|