Compare commits
6 Commits
5b37e91db3
...
master
Author | SHA1 | Date | |
---|---|---|---|
5e3805b567
|
|||
5861836852
|
|||
30d0270901
|
|||
4d13416222
|
|||
2bf42162ef
|
|||
440c33b8e5
|
@@ -11,11 +11,10 @@ python -m pddnsc.cli
|
|||||||
либо в [docker](https://www.docker.com)/[podman](https://podman.io) (для запуска по расписанию в `cron`):
|
либо в [docker](https://www.docker.com)/[podman](https://podman.io) (для запуска по расписанию в `cron`):
|
||||||
|
|
||||||
~~~bash
|
~~~bash
|
||||||
docker build -t my/pddnsc .
|
|
||||||
docker run -v .state:/app/state:rw \
|
docker run -v .state:/app/state:rw \
|
||||||
-v .settings:/app/settings:ro \
|
-v .settings:/app/settings:ro \
|
||||||
-e SCHEDULE=@hourly \
|
-e SCHEDULE=@hourly \
|
||||||
my/pddnsc
|
gitea.b4tman.ru/b4tman/pddnsc
|
||||||
~~~
|
~~~
|
||||||
|
|
||||||
## Конфигурация
|
## Конфигурация
|
||||||
@@ -60,7 +59,7 @@ docker run -v .state:/app/state:rw \
|
|||||||
- `filters` - фильтры, если хоть один вернет ложь то программа ничего никуда не запишет и не отправит, например проверка, что ip адрес не изменился
|
- `filters` - фильтры, если хоть один вернет ложь то программа ничего никуда не запишет и не отправит, например проверка, что ip адрес не изменился
|
||||||
- `outputs` - модули вывода, например вывод в консоль, запись в файл или создание dns записей на сервере
|
- `outputs` - модули вывода, например вывод в консоль, запись в файл или создание dns записей на сервере
|
||||||
|
|
||||||
Все модули источников/фильтров/вывода работают конкурентно через `asyncio`.
|
Все модули источников/фильтров/вывода работают конкурентно через [asyncio](https://docs.python.org/3/library/asyncio.html#module-asyncio) и [httpx](https://www.python-httpx.org).
|
||||||
|
|
||||||
### Подробная документация
|
### Подробная документация
|
||||||
|
|
||||||
|
291
pddnsc/cli.py
291
pddnsc/cli.py
@@ -1,297 +1,10 @@
|
|||||||
""" модуль запуска """
|
""" модуль запуска """
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import asyncio
|
|
||||||
import toml
|
import toml
|
||||||
from .base import BaseFilterProvider, BaseSourceProvider, BaseOutputProvider, IPAddreses
|
import asyncio
|
||||||
from .plugins import use_plugins
|
|
||||||
from typing import Optional, NamedTuple
|
|
||||||
|
|
||||||
|
from pddnsc.core import app
|
||||||
class NeededAddrs(NamedTuple):
|
|
||||||
ipv4: bool
|
|
||||||
ipv6: bool
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_config(cls, config: dict) -> "NeededAddrs":
|
|
||||||
need_ipv4 = config.get("require_ipv4", False)
|
|
||||||
need_ipv6 = config.get("require_ipv6", False)
|
|
||||||
if "require_ipv4" not in config and "require_ipv6" not in config:
|
|
||||||
need_ipv4 = need_ipv6 = True
|
|
||||||
return cls(need_ipv4, need_ipv6)
|
|
||||||
|
|
||||||
|
|
||||||
def is_valid_addreses(addrs: IPAddreses, config: dict) -> bool:
|
|
||||||
"""Проверка валидности IP адресов
|
|
||||||
|
|
||||||
Args:
|
|
||||||
addrs (IPAddreses): IP адреса - результат одного из источников
|
|
||||||
config (dict): общая конфигурация
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: валиден или нет
|
|
||||||
"""
|
|
||||||
result = addrs.ipv4 or addrs.ipv6
|
|
||||||
if config.get("require_ipv4"):
|
|
||||||
result = result and addrs.ipv4
|
|
||||||
if config.get("require_ipv6"):
|
|
||||||
result = result and addrs.ipv6
|
|
||||||
return bool(result)
|
|
||||||
|
|
||||||
|
|
||||||
def is_ipv4_ok(ipv4: str, config: dict) -> bool:
|
|
||||||
"""Проверка IPv4 адреса, подходит или нет
|
|
||||||
|
|
||||||
Args:
|
|
||||||
ipv4 (str): IPv4 адрес
|
|
||||||
config (dict): общая конфигурация
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: подходит или нет
|
|
||||||
"""
|
|
||||||
return bool(ipv4) if NeededAddrs.from_config(config).ipv4 else True
|
|
||||||
|
|
||||||
|
|
||||||
def is_ipv6_ok(ipv6: str, config: dict) -> bool:
|
|
||||||
"""Проверка IPv6 адреса, подходит или нет
|
|
||||||
|
|
||||||
Args:
|
|
||||||
ipv6 (str): IPv6 адрес
|
|
||||||
config (dict): общая конфигурация
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: подходит или нет
|
|
||||||
"""
|
|
||||||
return bool(ipv6) if NeededAddrs.from_config(config).ipv6 else True
|
|
||||||
|
|
||||||
|
|
||||||
async def get_ip_addresses(config: dict) -> Optional[IPAddreses]:
|
|
||||||
"""Получение всех IP адресов из всех источников
|
|
||||||
|
|
||||||
Args:
|
|
||||||
config (dict): общая конфигурация
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Optional[IPAddreses]: результат получения, либо None
|
|
||||||
"""
|
|
||||||
|
|
||||||
unit_mode = config.get("unit_mode", False)
|
|
||||||
if unit_mode:
|
|
||||||
result = await get_ip_addresses_unit(config)
|
|
||||||
else:
|
|
||||||
result = await get_ip_addresses_any(config)
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
async def get_ip_addresses_any(config: dict) -> Optional[IPAddreses]:
|
|
||||||
"""Получение всех IP адресов из всех источников (режим any)
|
|
||||||
|
|
||||||
Получает разные адреса от любых источников
|
|
||||||
|
|
||||||
Args:
|
|
||||||
config (dict): общая конфигурация
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Optional[IPAddreses]: результат получения, либо None
|
|
||||||
"""
|
|
||||||
need = NeededAddrs.from_config(config)
|
|
||||||
providers = BaseSourceProvider.registred.values()
|
|
||||||
ip_addresses, is_done = None, False
|
|
||||||
last_src, last_ipv4, last_ipv6 = "", "", ""
|
|
||||||
ok_ipv4, ok_ipv6 = False, False
|
|
||||||
drop = []
|
|
||||||
pending = []
|
|
||||||
if need.ipv4:
|
|
||||||
pending += [
|
|
||||||
asyncio.create_task(p.fetch_v4(), name=f"{p.name}.v4") for p in providers
|
|
||||||
]
|
|
||||||
if need.ipv6:
|
|
||||||
pending += [
|
|
||||||
asyncio.create_task(p.fetch_v6(), name=f"{p.name}.v6") for p in providers
|
|
||||||
]
|
|
||||||
while not is_done and pending:
|
|
||||||
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
|
||||||
for x in done:
|
|
||||||
ip_addr = x.result()
|
|
||||||
if x.get_name().endswith(".v6"):
|
|
||||||
last_ipv6 = last_ipv6 if ok_ipv6 else ip_addr
|
|
||||||
else:
|
|
||||||
last_ipv4 = last_ipv4 if ok_ipv4 else ip_addr
|
|
||||||
if config.get("debug"):
|
|
||||||
print("debug:", "get", x.get_name(), ip_addr)
|
|
||||||
last_src = x.get_name().rsplit(".", maxsplit=1)[0]
|
|
||||||
ok_ipv4 = is_ipv4_ok(last_ipv4, config)
|
|
||||||
ok_ipv6 = is_ipv6_ok(last_ipv6, config)
|
|
||||||
pending_v4 = [*filter(lambda i: i.get_name().endswith(".v4"), pending)]
|
|
||||||
pending_v6 = [*filter(lambda i: i.get_name().endswith(".v6"), pending)]
|
|
||||||
if ok_ipv4 and pending_v4:
|
|
||||||
drop += pending_v4
|
|
||||||
pending = pending_v6
|
|
||||||
for i in pending_v4:
|
|
||||||
i.cancel()
|
|
||||||
pending_v4 = []
|
|
||||||
if ok_ipv6 and pending_v6:
|
|
||||||
drop += pending_v6
|
|
||||||
pending = pending_v4
|
|
||||||
for i in pending_v6:
|
|
||||||
i.cancel()
|
|
||||||
pending_v6 = []
|
|
||||||
if not (ok_ipv4 and ok_ipv6):
|
|
||||||
continue
|
|
||||||
ip_addresses = IPAddreses(last_src, last_ipv4, last_ipv6)
|
|
||||||
if is_valid_addreses(ip_addresses, config):
|
|
||||||
is_done = True
|
|
||||||
break
|
|
||||||
ip_addresses = None
|
|
||||||
|
|
||||||
if not (ok_ipv4 and ok_ipv6):
|
|
||||||
ip_addresses = IPAddreses(last_src, last_ipv4, last_ipv6)
|
|
||||||
|
|
||||||
drop = drop + list(pending)
|
|
||||||
if drop:
|
|
||||||
gather = asyncio.gather(*drop)
|
|
||||||
gather.cancel()
|
|
||||||
try:
|
|
||||||
await gather
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
return ip_addresses
|
|
||||||
|
|
||||||
|
|
||||||
async def get_ip_addresses_unit(config: dict) -> Optional[IPAddreses]:
|
|
||||||
"""Получение всех IP адресов из всех источников (режим unit)
|
|
||||||
|
|
||||||
Получает адреса только от одного источника
|
|
||||||
|
|
||||||
Args:
|
|
||||||
config (dict): общая конфигурация
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Optional[IPAddreses]: результат получения, либо None
|
|
||||||
"""
|
|
||||||
providers = BaseSourceProvider.registred.values()
|
|
||||||
ip_addresses = None
|
|
||||||
is_done = False
|
|
||||||
pending = [asyncio.create_task(p.fetch_all(), name=p.name) for p in providers]
|
|
||||||
while not is_done and pending:
|
|
||||||
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
|
||||||
for x in done:
|
|
||||||
ip_addresses = x.result()
|
|
||||||
if is_valid_addreses(ip_addresses, config):
|
|
||||||
is_done = True
|
|
||||||
break
|
|
||||||
ip_addresses = None
|
|
||||||
|
|
||||||
if pending:
|
|
||||||
gather = asyncio.gather(*pending)
|
|
||||||
gather.cancel()
|
|
||||||
try:
|
|
||||||
await gather
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
return ip_addresses
|
|
||||||
|
|
||||||
|
|
||||||
async def check_ip_addresses(ip_addresses: IPAddreses) -> bool:
|
|
||||||
"""Проверка результата получения IP адресов с помощью фильтров
|
|
||||||
|
|
||||||
Args:
|
|
||||||
ip_addresses (IPAddreses): IP адреса
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: корректны ли адреса (изменились ли они),
|
|
||||||
надо ли продолжать обработку и отправлять их на сервер
|
|
||||||
"""
|
|
||||||
providers = BaseFilterProvider.registred.values()
|
|
||||||
result = True
|
|
||||||
failed = ""
|
|
||||||
pending = [
|
|
||||||
asyncio.create_task(p.check(*ip_addresses), name=p.name) for p in providers
|
|
||||||
]
|
|
||||||
while result and pending:
|
|
||||||
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
|
||||||
for x in done:
|
|
||||||
result = x.result()
|
|
||||||
if not result:
|
|
||||||
failed = x.get_name()
|
|
||||||
|
|
||||||
if pending:
|
|
||||||
gather = asyncio.gather(*pending)
|
|
||||||
gather.cancel()
|
|
||||||
try:
|
|
||||||
await gather
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
if not result:
|
|
||||||
print("failed filter:", failed)
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
async def send_ip_addreses(ip_addresses: IPAddreses):
|
|
||||||
"""Отправка адресов на все плагины вывода
|
|
||||||
|
|
||||||
Args:
|
|
||||||
ip_addresses (IPAddreses): IP адреса
|
|
||||||
"""
|
|
||||||
providers = BaseOutputProvider.registred.values()
|
|
||||||
await asyncio.gather(
|
|
||||||
*(
|
|
||||||
asyncio.create_task(p.set_addrs(*ip_addresses), name=p.name)
|
|
||||||
for p in providers
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def print_debug_info(config: dict):
|
|
||||||
"""Вывод всех зарегистрированных плагинов и другой отладочной информации"""
|
|
||||||
debug = config.get("debug", False)
|
|
||||||
if debug:
|
|
||||||
print("DEBUG info:")
|
|
||||||
print(
|
|
||||||
f"source classes: {[*BaseSourceProvider._childs]}, {[*map(str, BaseSourceProvider._childs.values())]}"
|
|
||||||
)
|
|
||||||
print(
|
|
||||||
f"filter classes: {[*BaseFilterProvider._childs]}, {[*map(str, BaseFilterProvider._childs.values())]}"
|
|
||||||
)
|
|
||||||
print(
|
|
||||||
f"output classes: {[*BaseOutputProvider._childs]}, {[*map(str, BaseOutputProvider._childs.values())]}"
|
|
||||||
)
|
|
||||||
print(
|
|
||||||
f"source providers: {[*BaseSourceProvider.registred]}, {[*map(str, BaseSourceProvider.registred.values())]}"
|
|
||||||
)
|
|
||||||
print(
|
|
||||||
f"filter providers: {[*BaseFilterProvider.registred]}, {[*map(str, BaseFilterProvider.registred.values())]}"
|
|
||||||
)
|
|
||||||
print(
|
|
||||||
f"output providers: {[*BaseOutputProvider.registred]}, {[*map(str, BaseOutputProvider.registred.values())]}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def app(
|
|
||||||
config: dict, ipv4t: httpx.AsyncHTTPTransport, ipv6t: httpx.AsyncHTTPTransport
|
|
||||||
):
|
|
||||||
"""Запуск приложения
|
|
||||||
|
|
||||||
Args:
|
|
||||||
config (dict): общая конфигурация
|
|
||||||
ipv4t (httpx.AsyncHTTPTransport): транспорт IPv4
|
|
||||||
ipv6t (httpx.AsyncHTTPTransport): транспорт IPv6
|
|
||||||
"""
|
|
||||||
use_plugins(config, ipv4t, ipv6t)
|
|
||||||
|
|
||||||
print_debug_info(config)
|
|
||||||
|
|
||||||
ip_addreses = await get_ip_addresses(config)
|
|
||||||
if ip_addreses is None:
|
|
||||||
print("no IP addresses")
|
|
||||||
return
|
|
||||||
if not await check_ip_addresses(ip_addreses):
|
|
||||||
print("stop by filters")
|
|
||||||
return
|
|
||||||
await send_ip_addreses(ip_addreses)
|
|
||||||
print("done")
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
|
285
pddnsc/core.py
Normal file
285
pddnsc/core.py
Normal file
@@ -0,0 +1,285 @@
|
|||||||
|
import httpx
|
||||||
|
import asyncio
|
||||||
|
from .base import BaseFilterProvider, BaseSourceProvider, BaseOutputProvider, IPAddreses
|
||||||
|
from .plugins import use_plugins
|
||||||
|
from typing import Optional, NamedTuple
|
||||||
|
|
||||||
|
|
||||||
|
class NeededAddrs(NamedTuple):
|
||||||
|
ipv4: bool
|
||||||
|
ipv6: bool
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_config(cls, config: dict) -> "NeededAddrs":
|
||||||
|
need_ipv4 = config.get("require_ipv4", False)
|
||||||
|
need_ipv6 = config.get("require_ipv6", False)
|
||||||
|
if "require_ipv4" not in config and "require_ipv6" not in config:
|
||||||
|
need_ipv4 = need_ipv6 = True
|
||||||
|
return cls(need_ipv4, need_ipv6)
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_addreses(addrs: IPAddreses, config: dict) -> bool:
|
||||||
|
"""Проверка валидности IP адресов
|
||||||
|
|
||||||
|
Args:
|
||||||
|
addrs (IPAddreses): IP адреса - результат одного из источников
|
||||||
|
config (dict): общая конфигурация
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: валиден или нет
|
||||||
|
"""
|
||||||
|
result = addrs.ipv4 or addrs.ipv6
|
||||||
|
if config.get("require_ipv4"):
|
||||||
|
result = result and addrs.ipv4
|
||||||
|
if config.get("require_ipv6"):
|
||||||
|
result = result and addrs.ipv6
|
||||||
|
return bool(result)
|
||||||
|
|
||||||
|
|
||||||
|
def is_ipv4_ok(ipv4: str, config: dict) -> bool:
|
||||||
|
"""Проверка IPv4 адреса, подходит или нет
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ipv4 (str): IPv4 адрес
|
||||||
|
config (dict): общая конфигурация
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: подходит или нет
|
||||||
|
"""
|
||||||
|
return bool(ipv4) if NeededAddrs.from_config(config).ipv4 else True
|
||||||
|
|
||||||
|
|
||||||
|
def is_ipv6_ok(ipv6: str, config: dict) -> bool:
|
||||||
|
"""Проверка IPv6 адреса, подходит или нет
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ipv6 (str): IPv6 адрес
|
||||||
|
config (dict): общая конфигурация
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: подходит или нет
|
||||||
|
"""
|
||||||
|
return bool(ipv6) if NeededAddrs.from_config(config).ipv6 else True
|
||||||
|
|
||||||
|
|
||||||
|
async def get_ip_addresses(config: dict) -> Optional[IPAddreses]:
|
||||||
|
"""Получение всех IP адресов из всех источников
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config (dict): общая конфигурация
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[IPAddreses]: результат получения, либо None
|
||||||
|
"""
|
||||||
|
|
||||||
|
unit_mode = config.get("unit_mode", False)
|
||||||
|
if unit_mode:
|
||||||
|
result = await get_ip_addresses_unit(config)
|
||||||
|
else:
|
||||||
|
result = await get_ip_addresses_any(config)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
async def get_ip_addresses_any(config: dict) -> Optional[IPAddreses]:
|
||||||
|
"""Получение всех IP адресов из всех источников (режим any)
|
||||||
|
|
||||||
|
Получает разные адреса от любых источников
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config (dict): общая конфигурация
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[IPAddreses]: результат получения, либо None
|
||||||
|
"""
|
||||||
|
need = NeededAddrs.from_config(config)
|
||||||
|
providers = BaseSourceProvider.registred.values()
|
||||||
|
ip_addresses, is_done = None, False
|
||||||
|
last_src, last_ipv4, last_ipv6 = "", "", ""
|
||||||
|
ok_ipv4, ok_ipv6 = False, False
|
||||||
|
drop = []
|
||||||
|
pending = []
|
||||||
|
if need.ipv4:
|
||||||
|
pending += [
|
||||||
|
asyncio.create_task(p.fetch_v4(), name=f"{p.name}.v4") for p in providers
|
||||||
|
]
|
||||||
|
if need.ipv6:
|
||||||
|
pending += [
|
||||||
|
asyncio.create_task(p.fetch_v6(), name=f"{p.name}.v6") for p in providers
|
||||||
|
]
|
||||||
|
while not is_done and pending:
|
||||||
|
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
||||||
|
for x in done:
|
||||||
|
ip_addr = x.result()
|
||||||
|
if x.get_name().endswith(".v6"):
|
||||||
|
last_ipv6 = last_ipv6 if ok_ipv6 else ip_addr
|
||||||
|
else:
|
||||||
|
last_ipv4 = last_ipv4 if ok_ipv4 else ip_addr
|
||||||
|
if config.get("debug"):
|
||||||
|
print("debug:", "get", x.get_name(), ip_addr)
|
||||||
|
last_src = x.get_name().rsplit(".", maxsplit=1)[0]
|
||||||
|
ok_ipv4 = is_ipv4_ok(last_ipv4, config)
|
||||||
|
ok_ipv6 = is_ipv6_ok(last_ipv6, config)
|
||||||
|
pending_v4 = [*filter(lambda i: i.get_name().endswith(".v4"), pending)]
|
||||||
|
pending_v6 = [*filter(lambda i: i.get_name().endswith(".v6"), pending)]
|
||||||
|
if ok_ipv4 and pending_v4:
|
||||||
|
drop += pending_v4
|
||||||
|
pending = pending_v6
|
||||||
|
for i in pending_v4:
|
||||||
|
i.cancel()
|
||||||
|
pending_v4 = []
|
||||||
|
if ok_ipv6 and pending_v6:
|
||||||
|
drop += pending_v6
|
||||||
|
pending = pending_v4
|
||||||
|
for i in pending_v6:
|
||||||
|
i.cancel()
|
||||||
|
pending_v6 = []
|
||||||
|
if not (ok_ipv4 and ok_ipv6):
|
||||||
|
continue
|
||||||
|
ip_addresses = IPAddreses(last_src, last_ipv4, last_ipv6)
|
||||||
|
if is_valid_addreses(ip_addresses, config):
|
||||||
|
is_done = True
|
||||||
|
break
|
||||||
|
ip_addresses = None
|
||||||
|
|
||||||
|
if not (ok_ipv4 and ok_ipv6):
|
||||||
|
ip_addresses = IPAddreses(last_src, last_ipv4, last_ipv6)
|
||||||
|
|
||||||
|
drop = drop + list(pending)
|
||||||
|
if drop:
|
||||||
|
gather = asyncio.gather(*drop)
|
||||||
|
gather.cancel()
|
||||||
|
try:
|
||||||
|
await gather
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
return ip_addresses
|
||||||
|
|
||||||
|
|
||||||
|
async def get_ip_addresses_unit(config: dict) -> Optional[IPAddreses]:
|
||||||
|
"""Получение всех IP адресов из всех источников (режим unit)
|
||||||
|
|
||||||
|
Получает адреса только от одного источника
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config (dict): общая конфигурация
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[IPAddreses]: результат получения, либо None
|
||||||
|
"""
|
||||||
|
providers = BaseSourceProvider.registred.values()
|
||||||
|
ip_addresses = None
|
||||||
|
is_done = False
|
||||||
|
pending = [asyncio.create_task(p.fetch_all(), name=p.name) for p in providers]
|
||||||
|
while not is_done and pending:
|
||||||
|
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
||||||
|
for x in done:
|
||||||
|
ip_addresses = x.result()
|
||||||
|
if is_valid_addreses(ip_addresses, config):
|
||||||
|
is_done = True
|
||||||
|
break
|
||||||
|
ip_addresses = None
|
||||||
|
|
||||||
|
if pending:
|
||||||
|
gather = asyncio.gather(*pending)
|
||||||
|
gather.cancel()
|
||||||
|
try:
|
||||||
|
await gather
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
return ip_addresses
|
||||||
|
|
||||||
|
|
||||||
|
async def check_ip_addresses(ip_addresses: IPAddreses) -> bool:
|
||||||
|
"""Проверка результата получения IP адресов с помощью фильтров
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ip_addresses (IPAddreses): IP адреса
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: корректны ли адреса (изменились ли они),
|
||||||
|
надо ли продолжать обработку и отправлять их на сервер
|
||||||
|
"""
|
||||||
|
providers = BaseFilterProvider.registred.values()
|
||||||
|
result = True
|
||||||
|
failed = ""
|
||||||
|
pending = [
|
||||||
|
asyncio.create_task(p.check(*ip_addresses), name=p.name) for p in providers
|
||||||
|
]
|
||||||
|
while result and pending:
|
||||||
|
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
||||||
|
for x in done:
|
||||||
|
result = x.result()
|
||||||
|
if not result:
|
||||||
|
failed = x.get_name()
|
||||||
|
|
||||||
|
if pending:
|
||||||
|
gather = asyncio.gather(*pending)
|
||||||
|
gather.cancel()
|
||||||
|
try:
|
||||||
|
await gather
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if not result:
|
||||||
|
print("failed filter:", failed)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
async def send_ip_addreses(ip_addresses: IPAddreses):
|
||||||
|
"""Отправка адресов на все плагины вывода
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ip_addresses (IPAddreses): IP адреса
|
||||||
|
"""
|
||||||
|
providers = BaseOutputProvider.registred.values()
|
||||||
|
await asyncio.gather(
|
||||||
|
*(
|
||||||
|
asyncio.create_task(p.set_addrs(*ip_addresses), name=p.name)
|
||||||
|
for p in providers
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def print_debug_info(config: dict):
|
||||||
|
"""Вывод всех зарегистрированных плагинов и другой отладочной информации"""
|
||||||
|
|
||||||
|
def format_registred(name, base):
|
||||||
|
result = f"{name}:\n"
|
||||||
|
result += f" classes: {[*base._childs]}\n"
|
||||||
|
result += f" .values: {[*map(str, base._childs.values())]}\n"
|
||||||
|
result += f" providers: {[*base.registred]}\n"
|
||||||
|
result += f" .values: {[*map(str, base.registred.values())]}\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
if config.get("debug", False):
|
||||||
|
print("DEBUG ->")
|
||||||
|
bases = BaseSourceProvider, BaseFilterProvider, BaseOutputProvider
|
||||||
|
for info in map(format_registred, "sources filters outputs".split(), bases):
|
||||||
|
print(info)
|
||||||
|
print("DEBUG <-")
|
||||||
|
|
||||||
|
|
||||||
|
async def app(
|
||||||
|
config: dict, ipv4t: httpx.AsyncHTTPTransport, ipv6t: httpx.AsyncHTTPTransport
|
||||||
|
):
|
||||||
|
"""Запуск приложения
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config (dict): общая конфигурация
|
||||||
|
ipv4t (httpx.AsyncHTTPTransport): транспорт IPv4
|
||||||
|
ipv6t (httpx.AsyncHTTPTransport): транспорт IPv6
|
||||||
|
"""
|
||||||
|
use_plugins(config, ipv4t, ipv6t)
|
||||||
|
|
||||||
|
print_debug_info(config)
|
||||||
|
|
||||||
|
ip_addreses = await get_ip_addresses(config)
|
||||||
|
if ip_addreses is None:
|
||||||
|
print("no IP addresses")
|
||||||
|
return
|
||||||
|
if not await check_ip_addresses(ip_addreses):
|
||||||
|
print("stop by filters")
|
||||||
|
return
|
||||||
|
await send_ip_addreses(ip_addreses)
|
||||||
|
print("done")
|
@@ -1,4 +1,3 @@
|
|||||||
import asyncio
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import aiofiles
|
import aiofiles
|
||||||
@@ -7,63 +6,79 @@ from os.path import isfile
|
|||||||
from pddnsc.base import BaseFilterProvider
|
from pddnsc.base import BaseFilterProvider
|
||||||
|
|
||||||
|
|
||||||
class StateHashFilter(BaseFilterProvider):
|
class GenericTextFileFilter(BaseFilterProvider):
|
||||||
"""Проверка на то что хотябы один IP адрес изменился по хешу сохраненному в файле
|
"""Проверка на то что хотябы один IP адрес изменился по сравнению с текстом в файле
|
||||||
|
|
||||||
Конфигурация:
|
Конфигурация:
|
||||||
|
|
||||||
- filepath: имя файла
|
- filepath: имя файла
|
||||||
|
- encoding: кодировка, по умолчанию "utf-8"
|
||||||
|
- mode: режим открытия, по умолчанию "r"
|
||||||
|
- check_ipv4: проверять ли IPv4, по умолчанию нет если check_ipv6 есть в конфиге иначе да
|
||||||
|
- check_ipv6: проверять ли IPv6, по умолчанию нет если check_ipv4 есть в конфиге иначе да
|
||||||
"""
|
"""
|
||||||
|
|
||||||
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
|
def post_init(self):
|
||||||
if not isfile(self.config["filepath"]):
|
super().post_init()
|
||||||
return True
|
self.filepath = self.config["filepath"]
|
||||||
|
self.encoding = self.config.get("encoding", "utf-8")
|
||||||
|
self.mode = self.config.get("mode", "r")
|
||||||
|
self.check_ipv4 = self.config.get("check_ipv4", False)
|
||||||
|
self.check_ipv6 = self.config.get("check_ipv6", False)
|
||||||
|
if "check_ipv4" not in self.config and "check_ipv4" not in self.config:
|
||||||
|
self.check_ipv4 = self.check_ipv6 = True
|
||||||
|
self.content = ""
|
||||||
|
|
||||||
new_state_str = (addr_v4 or "") + (addr_v6 or "")
|
async def read(self) -> str:
|
||||||
new_sha = hashlib.sha256(new_state_str.encode(encoding="utf-8"))
|
|
||||||
async with aiofiles.open(
|
async with aiofiles.open(
|
||||||
self.config["filepath"], mode="r", encoding="utf-8"
|
self.filepath, mode=self.mode, encoding=self.encoding
|
||||||
) as f:
|
) as f:
|
||||||
old_state_hash = await f.read()
|
self.content = await f.read()
|
||||||
|
|
||||||
return old_state_hash != new_sha.hexdigest()
|
|
||||||
|
|
||||||
|
|
||||||
class StateFileFilter(BaseFilterProvider):
|
|
||||||
"""Проверка на то что хотябы один IP адрес изменился по сравнению с данными в json файле
|
|
||||||
|
|
||||||
Конфигурация:
|
|
||||||
|
|
||||||
- filepath: имя файла
|
|
||||||
- check_ipv4: проверка ipv4 адреса
|
|
||||||
- check_ipv6: проверка ipv6 адреса
|
|
||||||
|
|
||||||
если нет ни одного параметра то проверка выполняется для всех адресов
|
|
||||||
"""
|
|
||||||
|
|
||||||
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
|
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
|
||||||
if not isfile(self.config["filepath"]):
|
lst = []
|
||||||
|
if self.check_ipv4:
|
||||||
|
lst.append(addr_v4)
|
||||||
|
if self.check_ipv4:
|
||||||
|
lst.append(addr_v6)
|
||||||
|
new_content = "\n".join(lst)
|
||||||
|
return new_content != self.content
|
||||||
|
|
||||||
|
async def check(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
|
||||||
|
if not isfile(self.filepath):
|
||||||
return True
|
return True
|
||||||
|
await self.read()
|
||||||
|
return await self.check_imp(source_provider, addr_v4, addr_v6)
|
||||||
|
|
||||||
new_state = {
|
|
||||||
"ipv4": addr_v4,
|
|
||||||
"ipv6": addr_v6,
|
|
||||||
}
|
|
||||||
|
|
||||||
async with aiofiles.open(
|
class StateHashFilter(GenericTextFileFilter):
|
||||||
self.config["filepath"], mode="r", encoding="utf-8"
|
"""Проверка на то что хотябы один IP адрес изменился по хешу сохраненному в файле"""
|
||||||
) as f:
|
|
||||||
old_state = json.loads(await f.read())
|
|
||||||
|
|
||||||
|
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
|
||||||
|
new_state_str = (self.check_ipv4 and addr_v4 or "") + (
|
||||||
|
self.check_ipv6 and addr_v6 or ""
|
||||||
|
)
|
||||||
|
new_sha = hashlib.sha256(new_state_str.encode(encoding=self.encoding))
|
||||||
|
return self.content != new_sha.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
class StateFileFilter(GenericTextFileFilter):
|
||||||
|
"""Проверка на то что хотябы один IP адрес изменился по сравнению с данными в json файле"""
|
||||||
|
|
||||||
|
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
|
||||||
|
new_state = {}
|
||||||
|
if self.check_ipv4:
|
||||||
|
new_state["ipv4"] = addr_v4 or ""
|
||||||
|
if self.check_ipv6:
|
||||||
|
new_state["ipv6"] = addr_v6 or ""
|
||||||
|
|
||||||
|
old_state = json.loads(self.content)
|
||||||
result = True
|
result = True
|
||||||
|
|
||||||
if "check_ipv4" not in self.config and "check_ipv4" not in self.config:
|
if self.check_ipv4:
|
||||||
return new_state != old_state
|
|
||||||
|
|
||||||
if self.config.get("check_ipv4", False):
|
|
||||||
result = result and new_state["ipv4"] != old_state["ipv4"]
|
result = result and new_state["ipv4"] != old_state["ipv4"]
|
||||||
|
|
||||||
if self.config.get("check_ipv6", False):
|
if self.check_ipv6:
|
||||||
result = result and new_state["ipv6"] != old_state["ipv6"]
|
result = result and new_state["ipv6"] != old_state["ipv6"]
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
@@ -5,38 +5,70 @@ import hashlib
|
|||||||
from pddnsc.base import BaseOutputProvider
|
from pddnsc.base import BaseOutputProvider
|
||||||
|
|
||||||
|
|
||||||
class StateFile(BaseOutputProvider):
|
class GenericTextFile(BaseOutputProvider):
|
||||||
"""Схранение всех IP адресов в json файл
|
"""Сохранение IP адресов в текстовый файл
|
||||||
|
|
||||||
Конфигурация:
|
Конфигурация:
|
||||||
|
|
||||||
- filepath: имя файла
|
- filepath: имя файла
|
||||||
|
- encoding: кодировка, по умолчанию "utf-8"
|
||||||
|
- mode: режим открытия, по умолчанию "w"
|
||||||
|
- save_ipv4: сохранять ли IPv4, по умолчанию нет если save_ipv6 есть в конфиге иначе да
|
||||||
|
- save_ipv6: сохранять ли IPv6, по умолчанию нет если save_ipv4 есть в конфиге иначе да
|
||||||
"""
|
"""
|
||||||
|
|
||||||
async def set_addrs_imp(self, source_provider: str, addr_v4: str, addr_v6: str):
|
def post_init(self):
|
||||||
state = {
|
super().post_init()
|
||||||
"ipv4": addr_v4 or "",
|
self.filepath = self.config["filepath"]
|
||||||
"ipv6": addr_v6 or "",
|
self.encoding = self.config.get("encoding", "utf-8")
|
||||||
}
|
self.mode = self.config.get("mode", "w")
|
||||||
state_str = json.dumps(state)
|
self.save_ipv4 = self.config.get("save_ipv4", False)
|
||||||
|
self.save_ipv6 = self.config.get("save_ipv6", False)
|
||||||
|
if "save_ipv4" not in self.config and "save_ipv4" not in self.config:
|
||||||
|
self.save_ipv4 = self.save_ipv6 = True
|
||||||
|
self.content = ""
|
||||||
|
|
||||||
|
async def read(self):
|
||||||
|
async with aiofiles.open(self.filepath, mode="r", encoding=self.encoding) as f:
|
||||||
|
self.content = await f.read()
|
||||||
|
|
||||||
|
def set_content(self, ipv4: str, ipv6: str):
|
||||||
|
lst = []
|
||||||
|
if self.save_ipv4:
|
||||||
|
lst.append(ipv4)
|
||||||
|
if self.save_ipv6:
|
||||||
|
lst.append(ipv6)
|
||||||
|
self.content = "\n".join(lst)
|
||||||
|
|
||||||
|
async def write(self):
|
||||||
async with aiofiles.open(
|
async with aiofiles.open(
|
||||||
self.config["filepath"], mode="w", encoding="utf-8"
|
self.filepath, mode=self.mode, encoding=self.encoding
|
||||||
) as f:
|
) as f:
|
||||||
await f.write(state_str)
|
await f.write(self.content)
|
||||||
|
|
||||||
|
|
||||||
class StateHashFile(BaseOutputProvider):
|
|
||||||
"""Сохранение хеша от всех IP адресов в файл
|
|
||||||
|
|
||||||
Конфигурация:
|
|
||||||
|
|
||||||
- filepath: имя файла
|
|
||||||
"""
|
|
||||||
|
|
||||||
async def set_addrs_imp(self, source_provider: str, addr_v4: str, addr_v6: str):
|
async def set_addrs_imp(self, source_provider: str, addr_v4: str, addr_v6: str):
|
||||||
state_str = (addr_v4 or "") + (addr_v6 or "")
|
await self.set_content(addr_v4, addr_v6)
|
||||||
sha = hashlib.sha256(state_str.encode(encoding="utf-8"))
|
await self.write()
|
||||||
async with aiofiles.open(
|
|
||||||
self.config["filepath"], mode="w", encoding="utf-8"
|
|
||||||
) as f:
|
class StateFile(GenericTextFile):
|
||||||
await f.write(sha.hexdigest())
|
"""Сохранение всех IP адресов в json файл"""
|
||||||
|
|
||||||
|
async def set_content(self, addr_v4: str, addr_v6: str):
|
||||||
|
state = {}
|
||||||
|
if self.save_ipv4:
|
||||||
|
state["ipv4"] = addr_v4 or ""
|
||||||
|
if self.save_ipv6:
|
||||||
|
state["ipv6"] = addr_v6 or ""
|
||||||
|
self.content = json.dumps(state)
|
||||||
|
|
||||||
|
|
||||||
|
class StateHashFile(GenericTextFile):
|
||||||
|
"""Сохранение хеша от всех IP адресов в файл"""
|
||||||
|
|
||||||
|
async def set_content(self, addr_v4: str, addr_v6: str):
|
||||||
|
state_str = (self.save_ipv4 and addr_v4 or "") + (
|
||||||
|
self.save_ipv6 and addr_v6 or ""
|
||||||
|
)
|
||||||
|
sha = hashlib.sha256(state_str.encode(encoding=self.encoding))
|
||||||
|
self.content = sha.hexdigest()
|
||||||
|
@@ -3,23 +3,28 @@
|
|||||||
from httpx import AsyncHTTPTransport
|
from httpx import AsyncHTTPTransport
|
||||||
from .base import BaseSourceProvider, BaseFilterProvider, BaseOutputProvider
|
from .base import BaseSourceProvider, BaseFilterProvider, BaseOutputProvider
|
||||||
from . import sources
|
from . import sources
|
||||||
from . import outputs
|
|
||||||
from . import filters
|
from . import filters
|
||||||
|
from . import outputs
|
||||||
|
|
||||||
|
|
||||||
|
def unused():
|
||||||
|
"""Чтобы убрать предупреждение о неиспользуемых импортах"""
|
||||||
|
return sources, filters, outputs
|
||||||
|
|
||||||
|
|
||||||
def use_plugins(config: dict, ipv4t: AsyncHTTPTransport, ipv6t: AsyncHTTPTransport):
|
def use_plugins(config: dict, ipv4t: AsyncHTTPTransport, ipv6t: AsyncHTTPTransport):
|
||||||
"""Регистрация всех плагинов указаных в конфигурации"""
|
"""Регистрация всех плагинов указаных в конфигурации"""
|
||||||
for source_name in config["sources"]:
|
for source_name in config.get("sources", []):
|
||||||
BaseSourceProvider.register_provider(
|
BaseSourceProvider.register_provider(
|
||||||
source_name, config["sources"][source_name], ipv4t, ipv6t
|
source_name, config["sources"][source_name], ipv4t, ipv6t
|
||||||
)
|
)
|
||||||
|
|
||||||
for filter_name in config["filters"]:
|
for filter_name in config.get("filters", []):
|
||||||
BaseFilterProvider.register_provider(
|
BaseFilterProvider.register_provider(
|
||||||
filter_name, config["filters"][filter_name], ipv4t, ipv6t
|
filter_name, config["filters"][filter_name], ipv4t, ipv6t
|
||||||
)
|
)
|
||||||
|
|
||||||
for output_name in config["outputs"]:
|
for output_name in config.get("outputs", []):
|
||||||
BaseOutputProvider.register_provider(
|
BaseOutputProvider.register_provider(
|
||||||
output_name, config["outputs"][output_name], ipv4t, ipv6t
|
output_name, config["outputs"][output_name], ipv4t, ipv6t
|
||||||
)
|
)
|
||||||
|
Reference in New Issue
Block a user