Compare commits
7 Commits
bf63bff390
...
releases/v
| Author | SHA1 | Date | |
|---|---|---|---|
| f491c65455 | |||
| e71685aad9 | |||
| 98867d69a7 | |||
| 68f4b26f00 | |||
| 3b8e28e077 | |||
| 296b6404d2 | |||
| 38fdd347a5 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,2 +1,4 @@
|
|||||||
src/config_manager/__pycache__/basic_application.cpython-312.pyc
|
__pycache__
|
||||||
venv/
|
venv/
|
||||||
|
.vscode/
|
||||||
|
log*.log
|
||||||
|
|||||||
@@ -1,3 +1,24 @@
|
|||||||
[build-system]
|
[build-system]
|
||||||
requires = ["setuptools>=42"]
|
requires = ["setuptools>=61.0.0"]
|
||||||
build-backend = "setuptools.build_meta"
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "config_manager"
|
||||||
|
version = "1.1.0"
|
||||||
|
description = "Config manager for building applications"
|
||||||
|
authors = [
|
||||||
|
{ name = "Aleksei Zosimov", email = "lesha.spb@gmail.com" }
|
||||||
|
]
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.8"
|
||||||
|
dependencies = [
|
||||||
|
"PyYAML>=6.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.urls]
|
||||||
|
Homepage = "https://git.lesha.spb.ru/alex/config_manager"
|
||||||
|
Documentation = "https://git.lesha.spb.ru/alex/config_manager"
|
||||||
|
Repository = "https://git.lesha.spb.ru/alex/config_manager"
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
24
setup.cfg
24
setup.cfg
@@ -1,24 +0,0 @@
|
|||||||
[metadata]
|
|
||||||
name = config_manager
|
|
||||||
version = 1.0.1
|
|
||||||
author = Aleksei Zosimov
|
|
||||||
author_email = lesha.spb@gmail.com
|
|
||||||
description = Base application with configuration and logging features.
|
|
||||||
long_description = file: README.md
|
|
||||||
long_description_content_type = text/markdown
|
|
||||||
url = https://git.lesha.spb.ru/alex/config_manager
|
|
||||||
project_urls =
|
|
||||||
Bug Tracker = https://git.lesha.spb.ru/alex/config_manager/issues
|
|
||||||
classifiers =
|
|
||||||
Programming Language :: Python :: 3
|
|
||||||
License :: OSI Approved :: MIT License
|
|
||||||
Operating System :: OS Independent
|
|
||||||
|
|
||||||
[options]
|
|
||||||
package_dir =
|
|
||||||
= src
|
|
||||||
packages = find:
|
|
||||||
python_requires = >=3.10
|
|
||||||
|
|
||||||
[options.packages.find]
|
|
||||||
where = src
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
from config_manager.config_manager import ConfigManager
|
|
||||||
2
src/basic_application/__init__.py
Normal file
2
src/basic_application/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
from .config_manager import ConfigManager
|
||||||
|
from .log_manager import LogManager
|
||||||
137
src/basic_application/config_manager.py
Normal file
137
src/basic_application/config_manager.py
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
import logging
|
||||||
|
import logging.config
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import yaml
|
||||||
|
import os
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from .log_manager import LogManager
|
||||||
|
|
||||||
|
class ConfigManager:
|
||||||
|
DEFAULT_UPDATE_INTERVAL = 5.0
|
||||||
|
DEFAULT_WORK_INTERVAL = 2.0
|
||||||
|
|
||||||
|
def __init__(self, path: str, log_manager: Optional[LogManager] = None):
|
||||||
|
self.path = path
|
||||||
|
self.config: Any = None
|
||||||
|
self._last_hash = None
|
||||||
|
self.update_interval = self.DEFAULT_UPDATE_INTERVAL
|
||||||
|
self.work_interval = self.DEFAULT_WORK_INTERVAL
|
||||||
|
self._halt = asyncio.Event()
|
||||||
|
self._task: Optional[asyncio.Task] = None
|
||||||
|
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||||
|
|
||||||
|
self._log_manager = log_manager or LogManager()
|
||||||
|
self.logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
def _read_file_sync(self) -> str:
|
||||||
|
with open(self.path, "r", encoding="utf-8") as f:
|
||||||
|
return f.read()
|
||||||
|
|
||||||
|
async def _read_file_async(self) -> str:
|
||||||
|
return await asyncio.to_thread(self._read_file_sync)
|
||||||
|
|
||||||
|
def _parse_config(self, data) -> Any:
|
||||||
|
extension = os.path.splitext(self.path)[1].lower()
|
||||||
|
if extension in (".yaml", ".yml"):
|
||||||
|
return yaml.safe_load(data)
|
||||||
|
else:
|
||||||
|
return json.loads(data)
|
||||||
|
|
||||||
|
def _update_intervals_from_config(self) -> None:
|
||||||
|
if not self.config:
|
||||||
|
return
|
||||||
|
upd = self.config.get("update_interval")
|
||||||
|
wrk = self.config.get("work_interval")
|
||||||
|
|
||||||
|
if isinstance(upd, (int, float)) and upd > 0:
|
||||||
|
self.update_interval = float(upd)
|
||||||
|
self.logger.info(f"Update interval set to {self.update_interval} seconds")
|
||||||
|
else:
|
||||||
|
self.update_interval = self.DEFAULT_UPDATE_INTERVAL
|
||||||
|
|
||||||
|
if isinstance(wrk, (int, float)) and wrk > 0:
|
||||||
|
self.work_interval = float(wrk)
|
||||||
|
self.logger.info(f"Work interval set to {self.work_interval} seconds")
|
||||||
|
else:
|
||||||
|
self.work_interval = self.DEFAULT_WORK_INTERVAL
|
||||||
|
|
||||||
|
async def _update_config(self) -> None:
|
||||||
|
try:
|
||||||
|
data = await self._read_file_async()
|
||||||
|
current_hash = hash(data)
|
||||||
|
if current_hash != self._last_hash:
|
||||||
|
new_config = self._parse_config(data)
|
||||||
|
self.config = new_config
|
||||||
|
self._last_hash = current_hash
|
||||||
|
|
||||||
|
self._log_manager.apply_config(new_config)
|
||||||
|
self._update_intervals_from_config()
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error(f"Error reading/parsing config file: {e}")
|
||||||
|
|
||||||
|
def execute(self) -> None:
|
||||||
|
"""
|
||||||
|
Метод для переопределения в подклассах.
|
||||||
|
Здесь может быть блокирующая работа.
|
||||||
|
Запускается в отдельном потоке.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def _worker_loop(self) -> None:
|
||||||
|
while not self._halt.is_set():
|
||||||
|
await asyncio.to_thread(self.execute)
|
||||||
|
await asyncio.sleep(self.work_interval)
|
||||||
|
|
||||||
|
async def _periodic_update_loop(self) -> None:
|
||||||
|
while not self._halt.is_set():
|
||||||
|
await self._update_config()
|
||||||
|
await asyncio.sleep(self.update_interval)
|
||||||
|
|
||||||
|
async def _run(self) -> None:
|
||||||
|
"""Внутренняя корутина, запускающая все циклы"""
|
||||||
|
self._halt.clear()
|
||||||
|
self.logger.info("ConfigManager started")
|
||||||
|
try:
|
||||||
|
await asyncio.gather(
|
||||||
|
self._worker_loop(),
|
||||||
|
self._periodic_update_loop()
|
||||||
|
)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
self.logger.info("ConfigManager tasks cancelled")
|
||||||
|
finally:
|
||||||
|
self.logger.info("ConfigManager stopped")
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
"""Запускает менеджер конфигурации в текущем event loop"""
|
||||||
|
if self._task is not None and not self._task.done():
|
||||||
|
self.logger.warning("ConfigManager is already running")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
except RuntimeError:
|
||||||
|
self.logger.error("start() must be called from within an async context")
|
||||||
|
raise
|
||||||
|
|
||||||
|
self._task = self._loop.create_task(self._run())
|
||||||
|
self.logger.info("ConfigManager task created")
|
||||||
|
|
||||||
|
async def stop(self) -> None:
|
||||||
|
"""Останавливает менеджер конфигурации и ожидает завершения"""
|
||||||
|
if self._task is None:
|
||||||
|
self.logger.warning("ConfigManager is not running")
|
||||||
|
return
|
||||||
|
|
||||||
|
self.logger.info("ConfigManager stopping...")
|
||||||
|
self._halt.set()
|
||||||
|
|
||||||
|
try:
|
||||||
|
await self._task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self._task = None
|
||||||
|
self.logger.info("ConfigManager stopped successfully")
|
||||||
40
src/basic_application/log_manager.py
Normal file
40
src/basic_application/log_manager.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class LogManager:
|
||||||
|
"""
|
||||||
|
Управляет конфигурацией логирования приложения.
|
||||||
|
Применяет конфигурацию из словаря с обработкой ошибок.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.logger = logging.getLogger(__name__)
|
||||||
|
self._last_valid_config: Optional[dict] = None
|
||||||
|
|
||||||
|
def apply_config(self, config: dict) -> None:
|
||||||
|
"""
|
||||||
|
Применяет конфигурацию логирования из словаря.
|
||||||
|
При ошибке восстанавливает последний валидный конфиг.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config: Словарь с настройками логирования (из файла конфига)
|
||||||
|
"""
|
||||||
|
logging_config = config.get("log")
|
||||||
|
if not logging_config:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
logging.config.dictConfig(logging_config)
|
||||||
|
self._last_valid_config = logging_config
|
||||||
|
self.logger.info("Logging configuration applied")
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error(f"Error applying logging config: {e}")
|
||||||
|
|
||||||
|
# Если был предыдущий валидный конфиг, восстанавливаем его
|
||||||
|
if self._last_valid_config:
|
||||||
|
try:
|
||||||
|
logging.config.dictConfig(self._last_valid_config)
|
||||||
|
self.logger.info("Previous logging configuration restored")
|
||||||
|
except Exception as restore_error:
|
||||||
|
self.logger.error(f"Error restoring previous config: {restore_error}")
|
||||||
53
src/config.yaml
Normal file
53
src/config.yaml
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
# === Раздел с общими конфигурационными параметрами ===
|
||||||
|
runtime: 5
|
||||||
|
|
||||||
|
# === Логирование ===
|
||||||
|
log:
|
||||||
|
version: 1
|
||||||
|
disable_existing_loggers: False
|
||||||
|
|
||||||
|
formatters:
|
||||||
|
standard:
|
||||||
|
format: '%(asctime)s %(module)15s [%(levelname)8s]: %(message)s'
|
||||||
|
telegram:
|
||||||
|
format: '%(message)s'
|
||||||
|
|
||||||
|
handlers:
|
||||||
|
console:
|
||||||
|
level: DEBUG
|
||||||
|
formatter: standard
|
||||||
|
class: logging.StreamHandler
|
||||||
|
stream: ext://sys.stdout # Default is stderr
|
||||||
|
|
||||||
|
file:
|
||||||
|
level: DEBUG
|
||||||
|
formatter: standard
|
||||||
|
class: logging.handlers.RotatingFileHandler
|
||||||
|
filename: logs/log.log
|
||||||
|
mode: a
|
||||||
|
maxBytes: 500000
|
||||||
|
backupCount: 15
|
||||||
|
|
||||||
|
#telegram:
|
||||||
|
# level: CRITICAL
|
||||||
|
# formatter: telegram
|
||||||
|
# class: logging_telegram_handler.TelegramHandler
|
||||||
|
# chat_id: 211945135
|
||||||
|
# alias: "PDC"
|
||||||
|
|
||||||
|
|
||||||
|
# -- Логгеры --
|
||||||
|
loggers:
|
||||||
|
'':
|
||||||
|
handlers: [console, file]
|
||||||
|
level: INFO
|
||||||
|
propagate: False
|
||||||
|
|
||||||
|
__main__:
|
||||||
|
handlers: [console, file]
|
||||||
|
level: DEBUG
|
||||||
|
propagate: False
|
||||||
|
|
||||||
|
config_manager:
|
||||||
|
handlers: [console, file]
|
||||||
|
level: DEBUG
|
||||||
@@ -1,134 +0,0 @@
|
|||||||
import asyncio
|
|
||||||
import json
|
|
||||||
import yaml
|
|
||||||
import logging
|
|
||||||
import logging.config
|
|
||||||
from typing import Any
|
|
||||||
import os
|
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class ConfigManager:
|
|
||||||
DEFAULT_UPDATE_INTERVAL = 5.0
|
|
||||||
DEFAULT_WORK_INTERVAL = 2.0
|
|
||||||
|
|
||||||
def __init__(self, path: str):
|
|
||||||
self.path = path
|
|
||||||
self.config: Any = None
|
|
||||||
self._last_hash = None
|
|
||||||
self.update_interval = self.DEFAULT_UPDATE_INTERVAL
|
|
||||||
self.work_interval = self.DEFAULT_WORK_INTERVAL
|
|
||||||
self._halt = asyncio.Event()
|
|
||||||
|
|
||||||
def _read_file_sync(self) -> str:
|
|
||||||
with open(self.path, "r", encoding="utf-8") as f:
|
|
||||||
return f.read()
|
|
||||||
|
|
||||||
async def _read_file_async(self) -> str:
|
|
||||||
return await asyncio.to_thread(self._read_file_sync)
|
|
||||||
|
|
||||||
def _parse_config(self, data: str) -> Any:
|
|
||||||
ext = os.path.splitext(self.path)[1].lower()
|
|
||||||
if ext in (".yaml", ".yml"):
|
|
||||||
return yaml.safe_load(data)
|
|
||||||
else:
|
|
||||||
return json.loads(data)
|
|
||||||
|
|
||||||
def _update_intervals_from_config(self) -> None:
|
|
||||||
if not self.config:
|
|
||||||
return
|
|
||||||
# Берём интервалы из секции config обновления, с контролем типа и значений
|
|
||||||
upd = self.config.get("update_interval")
|
|
||||||
wrk = self.config.get("work_interval")
|
|
||||||
|
|
||||||
if isinstance(upd, (int, float)) and upd > 0:
|
|
||||||
self.update_interval = float(upd)
|
|
||||||
logger.info(f"Update interval set to {self.update_interval} seconds")
|
|
||||||
else:
|
|
||||||
self.update_interval = self.DEFAULT_UPDATE_INTERVAL
|
|
||||||
|
|
||||||
if isinstance(wrk, (int, float)) and wrk > 0:
|
|
||||||
self.work_interval = float(wrk)
|
|
||||||
logger.info(f"Work interval set to {self.work_interval} seconds")
|
|
||||||
else:
|
|
||||||
self.work_interval = self.DEFAULT_WORK_INTERVAL
|
|
||||||
|
|
||||||
def _apply_logging_config(self, config: dict) -> None:
|
|
||||||
try:
|
|
||||||
logging_config = config.get("logging")
|
|
||||||
if logging_config:
|
|
||||||
logging.config.dictConfig(logging_config)
|
|
||||||
logger.info("Logging configuration applied")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error applying logging config: {e}")
|
|
||||||
|
|
||||||
async def _update_config(self) -> None:
|
|
||||||
try:
|
|
||||||
data = await self._read_file_async()
|
|
||||||
current_hash = hash(data)
|
|
||||||
if current_hash != self._last_hash:
|
|
||||||
new_config = self._parse_config(data)
|
|
||||||
self.config = new_config
|
|
||||||
self._last_hash = current_hash
|
|
||||||
|
|
||||||
self._apply_logging_config(new_config)
|
|
||||||
self._update_intervals_from_config()
|
|
||||||
|
|
||||||
logger.info("Config updated: %s", self.config)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error reading/parsing config file: {e}")
|
|
||||||
|
|
||||||
def execute(self) -> None:
|
|
||||||
"""
|
|
||||||
Метод для переопределения в подклассах.
|
|
||||||
Здесь может быть блокирующая работа.
|
|
||||||
Запускается в отдельном потоке.
|
|
||||||
"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def _worker_loop(self) -> None:
|
|
||||||
while not self._halt.is_set():
|
|
||||||
await asyncio.to_thread(self.execute)
|
|
||||||
await asyncio.sleep(self.work_interval)
|
|
||||||
|
|
||||||
async def _periodic_update_loop(self) -> None:
|
|
||||||
while not self._halt.is_set():
|
|
||||||
await self._update_config()
|
|
||||||
await asyncio.sleep(self.update_interval)
|
|
||||||
|
|
||||||
async def start(self) -> None:
|
|
||||||
self._halt.clear()
|
|
||||||
logger.info("ConfigManager started")
|
|
||||||
await asyncio.gather(
|
|
||||||
self._worker_loop(),
|
|
||||||
self._periodic_update_loop()
|
|
||||||
)
|
|
||||||
|
|
||||||
def stop(self) -> None:
|
|
||||||
self._halt.set()
|
|
||||||
logger.info("ConfigManager stopping...")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Пример наследования и переопределения execute
|
|
||||||
class MyApp(ConfigManager):
|
|
||||||
def execute(self) -> None:
|
|
||||||
logger.info("Executing blocking work with config: %s", self.config)
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
app = MyApp("config.yaml") # Можно config.json или config.yaml
|
|
||||||
task = asyncio.create_task(app.start())
|
|
||||||
await asyncio.sleep(20)
|
|
||||||
app.stop()
|
|
||||||
await task
|
|
||||||
logger.info("Work finished.")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
logging.basicConfig(level=logging.INFO,
|
|
||||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
|
|
||||||
asyncio.run(main())
|
|
||||||
35
src/test.py
Normal file
35
src/test.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
from basic_application import ConfigManager
|
||||||
|
import logging
|
||||||
|
import asyncio
|
||||||
|
from typing import Optional
|
||||||
|
import os
|
||||||
|
os.chdir(os.path.dirname(__file__))
|
||||||
|
|
||||||
|
logger = logging.getLogger()
|
||||||
|
|
||||||
|
|
||||||
|
class MyApp(ConfigManager):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.iter = 0
|
||||||
|
|
||||||
|
|
||||||
|
def execute(self) -> None:
|
||||||
|
logger.info(f"current iteration {self.iter}")
|
||||||
|
self.iter += 1
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
app = MyApp("config.yaml")
|
||||||
|
app.start()
|
||||||
|
logger.info("App started")
|
||||||
|
await asyncio.sleep(20)
|
||||||
|
await app.stop()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user