You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

92 lines
2.6 KiB

import asyncio
import requests
import json
from typing import List
import os
import configparser
import aiohttp
async def write_config_files(
servers: list, path_to_template_file: str, path_for_config: str
) -> None:
template: str = ""
with open(path_to_template_file, "r") as file:
template = file.read()
config_full_path: str = os.path.abspath(path_for_config)
if not os.path.isdir(config_full_path):
os.mkdir(config_full_path)
for server in servers:
config_body: str = template.replace(
"server_name _;", f"server_name {server}.server.com;"
)
config_filename: str = f"{server}.conf"
with open(os.path.join(config_full_path, config_filename), "w") as file:
file.write(config_body)
async def send_async_request(cfg: dict, columns: list, limit: int = 1) -> None:
body = {"columns": columns, "limit": 1}
server = cfg["central_host_url"]
path_to_template_file = cfg["template"]
path_for_config = cfg["path_for_config"]
async with aiohttp.ClientSession() as session:
tasks = [session.get(server, json=body) for i in range(limit)]
responses = await asyncio.gather(*tasks)
for response in responses:
r = await response.json()
hosts = [i["hostname"] for i in r.get("result")]
await write_config_files(hosts, path_to_template_file, path_for_config)
def read_config(path_to_conf_file: str, section: str = "Main") -> dict:
"""
Считать конфиг с помощью `configparser`.
Parameters
----------
path_to_conf_file: str
Путь к файлу конфига. Можно указывать относительный.
section: str
Секция в конфиге, которую нужно считывать. По-умолчанию секция [Main].
Raises
------
KeyError
Если в конфиге не найдено указанной секции.
Returns
-------
dict
Словарь, из значений указанной секции.
"""
config = configparser.ConfigParser()
config.read(os.path.abspath(path_to_conf_file))
if section not in config.sections():
raise KeyError(f"Section {section} not found in config file!")
return dict(config.items(section))
async def main() -> None:
cnf = read_config("service.conf")
wait_sec: int = int(cnf["frequency_sec"])
while True:
await send_async_request(cnf, columns=["hostname"], limit=9999)
await asyncio.sleep(wait_sec)
if __name__ == "__main__":
asyncio.run(main())