bunkerweb/autoconf/Controller.py

99 lines
2.7 KiB
Python
Raw Normal View History

2022-06-03 15:24:14 +00:00
from abc import ABC, abstractmethod
from os import getenv
2022-06-03 15:24:14 +00:00
from time import sleep
from Config import Config
from logger import setup_logger
2022-06-03 15:24:14 +00:00
class Controller(ABC):
def __init__(self, ctrl_type, lock=None):
2022-06-03 15:24:14 +00:00
self._type = ctrl_type
self._instances = []
self._services = []
self._supported_config_types = [
"http",
"stream",
"server-http",
"server-stream",
"default-server-http",
"modsec",
"modsec-crs",
]
2022-06-03 15:24:14 +00:00
self._configs = {}
for config_type in self._supported_config_types:
2022-06-03 15:24:14 +00:00
self._configs[config_type] = {}
self._config = Config(ctrl_type, lock)
self.__logger = setup_logger("Controller", getenv("LOG_LEVEL", "INFO"))
2022-06-03 15:24:14 +00:00
def wait(self, wait_time):
while True:
2022-06-03 15:24:14 +00:00
self._instances = self.get_instances()
if len(self._instances) == 0:
self.__logger.warning(
f"No instance found, waiting {wait_time}s ...",
)
2022-06-03 15:24:14 +00:00
sleep(wait_time)
continue
all_ready = True
for instance in self._instances:
if not instance["health"]:
self.__logger.warning(
f"Instance {instance['name']} is not ready, waiting {wait_time}s ...",
)
2022-06-03 15:24:14 +00:00
sleep(wait_time)
all_ready = False
break
if all_ready:
2022-06-03 15:24:14 +00:00
break
return self._instances
@abstractmethod
def _get_controller_instances(self):
2022-06-03 15:24:14 +00:00
pass
2022-06-03 15:24:14 +00:00
@abstractmethod
def _to_instances(self, controller_instance):
2022-06-03 15:24:14 +00:00
pass
def get_instances(self):
2022-06-03 15:24:14 +00:00
instances = []
for controller_instance in self._get_controller_instances():
for instance in self._to_instances(controller_instance):
2022-06-03 15:24:14 +00:00
instances.append(instance)
return instances
@abstractmethod
def _get_controller_services(self):
2022-06-03 15:24:14 +00:00
pass
2022-06-03 15:24:14 +00:00
@abstractmethod
def _to_services(self, controller_service):
2022-06-03 15:24:14 +00:00
pass
@abstractmethod
def _get_static_services(self):
pass
def get_services(self):
2022-06-03 15:24:14 +00:00
services = []
for controller_service in self._get_controller_services():
for service in self._to_services(controller_service):
2022-06-03 15:24:14 +00:00
services.append(service)
for static_service in self._get_static_services():
services.append(static_service)
2022-06-03 15:24:14 +00:00
return services
@abstractmethod
def get_configs(self):
2022-06-03 15:24:14 +00:00
pass
@abstractmethod
def apply_config(self):
2022-06-03 15:24:14 +00:00
pass
@abstractmethod
def process_events(self):
pass