fmt + StateFileFilter

This commit is contained in:
Dmitry Belyaev 2024-02-20 10:40:23 +03:00
parent 773a4e0107
commit bbfb4f92af
Signed by: b4tman
GPG Key ID: 41A00BF15EA7E5F3
13 changed files with 128 additions and 79 deletions

View File

@ -2,6 +2,7 @@ import httpx
import asyncio import asyncio
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
class BaseSourceProvider(ABC): class BaseSourceProvider(ABC):
_childs = {} _childs = {}
registred = {} registred = {}
@ -46,12 +47,10 @@ class BaseSourceProvider(ABC):
cls.registred[name] = provider(name, config, ipv4t, ipv6t) cls.registred[name] = provider(name, config, ipv4t, ipv6t)
@abstractmethod @abstractmethod
async def fetch_v4(self) -> str: async def fetch_v4(self) -> str: ...
...
@abstractmethod @abstractmethod
async def fetch_v6(self) -> str: async def fetch_v6(self) -> str: ...
...
class BaseOutputProvider(ABC): class BaseOutputProvider(ABC):
@ -94,8 +93,8 @@ class BaseOutputProvider(ABC):
return await self.set_addrs_imp(source_provider, addr_v4, addr_v6) return await self.set_addrs_imp(source_provider, addr_v4, addr_v6)
@abstractmethod @abstractmethod
async def set_addrs_imp(self, source_provider, addr_v4, addr_v6): async def set_addrs_imp(self, source_provider, addr_v4, addr_v6): ...
...
class BaseFilterProvider(ABC): class BaseFilterProvider(ABC):
_childs = {} _childs = {}
@ -137,5 +136,4 @@ class BaseFilterProvider(ABC):
return await self.check_imp(source_provider, addr_v4, addr_v6) return await self.check_imp(source_provider, addr_v4, addr_v6)
@abstractmethod @abstractmethod
async def check_imp(self, source_provider, addr_v4, addr_v6): async def check_imp(self, source_provider, addr_v4, addr_v6): ...
...

View File

@ -3,9 +3,8 @@ import asyncio
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
import toml import toml
from .base import BaseFilterProvider, BaseSourceProvider, BaseOutputProvider from .base import BaseFilterProvider, BaseSourceProvider, BaseOutputProvider
from . import sources from .plugins import use_plugins
from . import outputs
from . import filters
async def source_task(): async def source_task():
providers = BaseSourceProvider.registred.values() providers = BaseSourceProvider.registred.values()
@ -30,12 +29,6 @@ async def source_task():
return result return result
async def output_task(providers, result):
providers = BaseOutputProvider.registred.values()
await asyncio.gather(
*(asyncio.create_task(p.set_addrs(*result), name=p.name) for p in providers)
)
async def filter_task(ip_result): async def filter_task(ip_result):
providers = BaseFilterProvider.registred.values() providers = BaseFilterProvider.registred.values()
result = True result = True
@ -62,22 +55,16 @@ async def filter_task(ip_result):
return result return result
async def output_task(result):
providers = BaseOutputProvider.registred.values()
await asyncio.gather(
*(asyncio.create_task(p.set_addrs(*result), name=p.name) for p in providers)
)
async def app(ipv4t, ipv6t): async def app(ipv4t, ipv6t):
config = toml.load("settings/config.toml") config = toml.load("settings/config.toml")
for source_name in config["sources"]: use_plugins(config, ipv4t, ipv6t)
BaseSourceProvider.register_provider(
source_name, config["sources"][source_name], ipv4t, ipv6t
)
for filter_name in config["filters"]:
BaseFilterProvider.register_provider(
filter_name, config["filters"][filter_name], ipv4t, ipv6t
)
for output_name in config["outputs"]:
BaseOutputProvider.register_provider(
output_name, config["outputs"][output_name], ipv4t, ipv6t
)
debug = config.get("debug", False) debug = config.get("debug", False)
if debug: if debug:
@ -100,13 +87,13 @@ async def app(ipv4t, ipv6t):
print( print(
f"output providers: {[*BaseOutputProvider.registred]}, {[*map(str, BaseOutputProvider.registred.values())]}" f"output providers: {[*BaseOutputProvider.registred]}, {[*map(str, BaseOutputProvider.registred.values())]}"
) )
#print(config)
result = await source_task() result = await source_task()
if not await filter_task(result): if not await filter_task(result):
print("stop by filters") print("stop by filters")
return return
await output_task(result) await output_task(result)
print("done")
async def main(): async def main():

View File

@ -1,3 +1,3 @@
from pddnsc.plugins import load_plugins from pddnsc.loaders import load_plugins
load_plugins(__file__) load_plugins(__file__)

View File

@ -6,9 +6,10 @@ from os.path import isfile
from pddnsc.base import BaseFilterProvider from pddnsc.base import BaseFilterProvider
class StateHashFilter(BaseFilterProvider): class StateHashFilter(BaseFilterProvider):
async def check_imp(self, source_provider, addr_v4, addr_v6): async def check_imp(self, source_provider, addr_v4, addr_v6):
if not isfile(self.config['filepath']): if not isfile(self.config["filepath"]):
return True return True
new_state = { new_state = {
@ -16,8 +17,39 @@ class StateHashFilter(BaseFilterProvider):
"ipv6": addr_v6 or "", "ipv6": addr_v6 or "",
} }
new_state_str = json.dumps(new_state) new_state_str = json.dumps(new_state)
new_sha = hashlib.sha256(new_state_str.encode(encoding='utf-8')) new_sha = hashlib.sha256(new_state_str.encode(encoding="utf-8"))
async with aiofiles.open(self.config['filepath'], mode='r', encoding='utf-8') as f: async with aiofiles.open(
self.config["filepath"], mode="r", encoding="utf-8"
) as f:
old_state_hash = await f.read() old_state_hash = await f.read()
return old_state_hash != new_sha.hexdigest() return old_state_hash != new_sha.hexdigest()
class StateFileFilter(BaseFilterProvider):
async def check_imp(self, source_provider, addr_v4, addr_v6):
if not isfile(self.config["filepath"]):
return True
new_state = {
"ipv4": addr_v4 or "",
"ipv6": addr_v6 or "",
}
async with aiofiles.open(
self.config["filepath"], mode="r", encoding="utf-8"
) as f:
old_state = json.loads(await f.read())
result = True
if "check_ipv4" not in self.config and "check_ipv4" not in self.config:
return new_state != old_state
if self.config.get("check_ipv4", False):
result = result and new_state["ipv4"] != old_state["ipv4"]
if self.config.get("check_ipv6", False):
result = result and new_state["ipv6"] != old_state["ipv6"]
return result

25
pddnsc/loaders.py Normal file
View File

@ -0,0 +1,25 @@
import os
import traceback
from importlib import util
def load_module(path):
name = os.path.split(path)[-1]
spec = util.spec_from_file_location(name, path)
module = util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def load_plugins(init_filepath):
dirpath = os.path.dirname(os.path.abspath(init_filepath))
for fname in os.listdir(dirpath):
if (
not fname.startswith(".")
and not fname.startswith("__")
and fname.endswith(".py")
):
try:
load_module(os.path.join(dirpath, fname))
except Exception:
traceback.print_exc()

View File

@ -1,3 +1,3 @@
from pddnsc.plugins import load_plugins from pddnsc.loaders import load_plugins
load_plugins(__file__) load_plugins(__file__)

View File

@ -2,6 +2,7 @@ import asyncio
from pddnsc.base import BaseOutputProvider from pddnsc.base import BaseOutputProvider
class JustPrint(BaseOutputProvider): class JustPrint(BaseOutputProvider):
async def set_addrs_imp(self, source_provider, addr_v4, addr_v6): async def set_addrs_imp(self, source_provider, addr_v4, addr_v6):
print(f">> {self.name}") print(f">> {self.name}")

View File

@ -13,7 +13,9 @@ class StateFile(BaseOutputProvider):
"ipv6": addr_v6 or "", "ipv6": addr_v6 or "",
} }
state_str = json.dumps(state) state_str = json.dumps(state)
async with aiofiles.open(self.config['filepath'], mode='w', encoding='utf-8') as f: async with aiofiles.open(
self.config["filepath"], mode="w", encoding="utf-8"
) as f:
await f.write(state_str) await f.write(state_str)
@ -24,6 +26,8 @@ class StateHashFile(BaseOutputProvider):
"ipv6": addr_v6 or "", "ipv6": addr_v6 or "",
} }
state_str = json.dumps(state) state_str = json.dumps(state)
sha = hashlib.sha256(state_str.encode(encoding='utf-8')) sha = hashlib.sha256(state_str.encode(encoding="utf-8"))
async with aiofiles.open(self.config['filepath'], mode='w', encoding='utf-8') as f: async with aiofiles.open(
self.config["filepath"], mode="w", encoding="utf-8"
) as f:
await f.write(sha.hexdigest()) await f.write(sha.hexdigest())

View File

@ -1,22 +1,21 @@
import os from .base import BaseSourceProvider, BaseFilterProvider, BaseOutputProvider
import traceback from . import sources
from importlib import util from . import outputs
from . import filters
def load_module(path): def use_plugins(config, ipv4t, ipv6t):
name = os.path.split(path)[-1] for source_name in config["sources"]:
spec = util.spec_from_file_location(name, path) BaseSourceProvider.register_provider(
module = util.module_from_spec(spec) source_name, config["sources"][source_name], ipv4t, ipv6t
spec.loader.exec_module(module) )
return module
for filter_name in config["filters"]:
BaseFilterProvider.register_provider(
filter_name, config["filters"][filter_name], ipv4t, ipv6t
)
def load_plugins(init_filepath): for output_name in config["outputs"]:
dirpath = os.path.dirname(os.path.abspath(init_filepath)) BaseOutputProvider.register_provider(
for fname in os.listdir(dirpath): output_name, config["outputs"][output_name], ipv4t, ipv6t
if not fname.startswith('.') and \ )
not fname.startswith('__') and fname.endswith('.py'):
try:
load_module(os.path.join(dirpath, fname))
except Exception:
traceback.print_exc()

View File

@ -1,3 +1,3 @@
from pddnsc.plugins import load_plugins from pddnsc.loaders import load_plugins
load_plugins(__file__) load_plugins(__file__)

View File

@ -3,29 +3,26 @@ import asyncio
from pddnsc.base import BaseSourceProvider from pddnsc.base import BaseSourceProvider
class DummySource(BaseSourceProvider): class DummySource(BaseSourceProvider):
async def fetch_v4(self) -> str: async def fetch_v4(self) -> str:
async with httpx.AsyncClient(transport=self.ipv4t) as client: result = await asyncio.sleep(self.config.get("delay", 1), result=None)
result = await asyncio.sleep(10, result=None)
result = await asyncio.sleep(10, result=None)
return result return result
async def fetch_v6(self) -> str: async def fetch_v6(self) -> str:
async with httpx.AsyncClient(transport=self.ipv6t) as client: result = await asyncio.sleep(self.config.get("delay", 1), result=None)
result = await asyncio.sleep(10, result=None)
result = await asyncio.sleep(10, result=None)
return result return result
class FakeSource(BaseSourceProvider): class FakeSource(BaseSourceProvider):
async def fetch_v4(self) -> str: async def fetch_v4(self) -> str:
async with httpx.AsyncClient(transport=self.ipv4t) as client:
result = await asyncio.sleep( result = await asyncio.sleep(
3.3, result=self.config.get("ipv4", "127.0.0.1") self.config.get("delay", 1), result=self.config.get("ipv4", "127.0.0.1")
) )
return result return result
async def fetch_v6(self) -> str: async def fetch_v6(self) -> str:
async with httpx.AsyncClient(transport=self.ipv6t) as client: result = await asyncio.sleep(
result = await asyncio.sleep(4.4, result=self.config.get("ipv6", "::1")) self.config.get("delay", 1), result=self.config.get("ipv6", "::1")
)
return result return result

View File

@ -2,6 +2,7 @@ import httpx
from pddnsc.base import BaseSourceProvider from pddnsc.base import BaseSourceProvider
class IPIFYSource(BaseSourceProvider): class IPIFYSource(BaseSourceProvider):
async def fetch_v4(self) -> str: async def fetch_v4(self) -> str:
async with httpx.AsyncClient(transport=self.ipv4t) as client: async with httpx.AsyncClient(transport=self.ipv4t) as client:

View File

@ -1,13 +1,18 @@
debug = true debug = true
[sources] [sources]
[sources.test1-src] [sources.ipfy]
provider = "IPIFYSource" provider = "IPIFYSource"
[sources.test2-src] [sources.fake]
provider = "FakeSource" provider = "FakeSource"
delay = 10
ipv6 = "fe80::1" ipv6 = "fe80::1"
[filters] [filters]
[filters.state-file]
provider = "StateFileFilter"
filepath = "state/state.json"
check_ipv4 = true
[filters.state-hash] [filters.state-hash]
provider = "StateHashFilter" provider = "StateHashFilter"
filepath = "state/hash.txt" filepath = "state/hash.txt"
@ -15,7 +20,7 @@ debug = true
[outputs] [outputs]
[outputs.print] [outputs.print]
provider = "JustPrint" provider = "JustPrint"
[outputs.file] [outputs.state-file]
provider = "StateFile" provider = "StateFile"
filepath = "state/state.json" filepath = "state/state.json"
[outputs.hash-file] [outputs.hash-file]