aido-smb-connector/app/main.py
2026-10-01 23:33:06 +02:00

84 lines
2.5 KiB
Python

"""Entry point: bootstrap auth, then run the sync loop on an interval."""
from __future__ import annotations
import logging
import signal
import sys
import time
from .config import load_config
from .onyx_client import OnyxClient, OnyxError
from .state import State
from .sync import sync_all
_stop = False
def _handle_signal(signum, _frame):
global _stop
logging.getLogger("smb").info("Received signal %s — finishing current cycle then exiting", signum)
_stop = True
def bootstrap_api_key(client: OnyxClient, state: State) -> None:
"""Ensure we have a usable API key. Preference order:
1. ONYX_API_KEY (already on the client) 2. cached key in the state file
3. create one via admin bootstrap credentials."""
if client.api_key:
return
if state.api_key:
client.api_key = state.api_key
return
key = client.create_api_key("AIDO SMB Connector")
state.api_key = key
state.save()
logging.getLogger("smb").info("Created and cached a new Onyx API key")
def main() -> int:
cfg = load_config()
logging.basicConfig(
level=getattr(logging, cfg.log_level, logging.INFO),
format="%(asctime)s %(levelname)-7s %(name)s | %(message)s",
)
log = logging.getLogger("smb")
signal.signal(signal.SIGTERM, _handle_signal)
signal.signal(signal.SIGINT, _handle_signal)
state = State.load(cfg.state_path)
client = OnyxClient(cfg.api_url, cfg.api_key, timeout=cfg.http_timeout)
client.set_admin_credentials(cfg.admin_email, cfg.admin_password)
try:
bootstrap_api_key(client, state)
except OnyxError as exc:
log.error("Could not obtain an API key: %s", exc)
return 2
log.info(
"AIDO SMB connector started: %d source(s), every %ds → %s",
len(cfg.sources), cfg.interval_seconds, cfg.api_url,
)
while not _stop:
started = time.time()
try:
sync_all(client, cfg, state)
except Exception as exc: # never crash the loop
log.exception("Sync cycle error: %s", exc)
elapsed = time.time() - started
log.info("Cycle finished in %.1fs; next in %ds", elapsed, cfg.interval_seconds)
# Sleep in small slices so SIGTERM is responsive.
remaining = cfg.interval_seconds
while remaining > 0 and not _stop:
time.sleep(min(2, remaining))
remaining -= 2
log.info("Shut down cleanly.")
return 0
if __name__ == "__main__":
sys.exit(main())